/**
 * Knowledge Add Command
 * Add knowledge entries to your knowledge base
 */

import { writeFileSync, readFileSync, existsSync, mkdirSync } from 'fs'
import { join } from 'path'
import { homedir } from 'os'

export interface AddOptions {
  content: string
  tags?: string[]
  category?: string
  title?: string
  source?: string
}

const KNOWLEDGE_DIR = join(homedir(), '.claude', 'knowledge')
const KNOWLEDGE_FILE = join(KNOWLEDGE_DIR, 'knowledge.json')

interface KnowledgeEntry {
  id: string
  title?: string
  content: string
  tags: string[]
  category: string
  source?: string
  timestamp: string
}

export async function handle(args: AddOptions, context: any): Promise<string> {
  const { content, tags = [], category = 'general', title, source } = args

  try {
    // Ensure knowledge directory exists
    if (!existsSync(KNOWLEDGE_DIR)) {
      mkdirSync(KNOWLEDGE_DIR, { recursive: true })
    }

    // Load existing knowledge
    let knowledge: KnowledgeEntry[] = []

    if (existsSync(KNOWLEDGE_FILE)) {
      const data = readFileSync(KNOWLEDGE_FILE, 'utf-8')
      knowledge = JSON.parse(data)
    }

    // Create new entry
    const entry: KnowledgeEntry = {
      id: generateId(),
      title,
      content,
      tags,
      category,
      source,
      timestamp: new Date().toISOString(),
    }

    knowledge.push(entry)

    // Save knowledge
    writeFileSync(KNOWLEDGE_FILE, JSON.stringify(knowledge, null, 2), 'utf-8')

    return `✓ Knowledge entry added (ID: ${entry.id})\n` +
           `  Category: ${category}\n` +
           `  Tags: ${tags.join(', ') || 'none'}\n` +
           `  Total entries: ${knowledge.length}`
  } catch (error: any) {
    throw new Error(`Failed to add knowledge: ${error.message}`)
  }
}

function generateId(): string {
  return Date.now().toString(36) + Math.random().toString(36).substr(2)
}

export default { handle }
