/**
 * Knowledge List Command
 * List all knowledge entries
 */

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

export interface ListOptions {
  category?: string
  tags?: string[]
}

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

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

export async function handle(args: ListOptions, context: any): Promise<string> {
  const { category, tags } = args

  try {
    if (!existsSync(KNOWLEDGE_FILE)) {
      return 'Knowledge base is empty. Add some knowledge first!'
    }

    const data = readFileSync(KNOWLEDGE_FILE, 'utf-8')
    const knowledge: KnowledgeEntry[] = JSON.parse(data)

    // Group by category
    const byCategory: Record<string, KnowledgeEntry[]> = {}

    for (const entry of knowledge) {
      if (category && entry.category !== category) continue
      if (tags && !tags.some(t => entry.tags.includes(t))) continue

      if (!byCategory[entry.category]) {
        byCategory[entry.category] = []
      }
      byCategory[entry.category].push(entry)
    }

    if (Object.keys(byCategory).length === 0) {
      return 'No entries found matching criteria'
    }

    // Format output
    const lines: string[] = []

    for (const [cat, entries] of Object.entries(byCategory)) {
      lines.push(`\n📁 ${cat} (${entries.length} entries)`)

      for (const entry of entries) {
        const title = entry.title || entry.content.slice(0, 50)
        const date = new Date(entry.timestamp).toLocaleDateString()
        lines.push(`  • ${title} [${entry.tags.join(', ') || 'no tags'}] - ${date}`)
      }
    }

    return `\n📚 Knowledge Base (${knowledge.length} total entries)\n${lines.join('\n')}`
  } catch (error: any) {
    throw new Error(`Failed to list knowledge: ${error.message}`)
  }
}

export default { handle }
