/**
 * Knowledge Export Command
 * Export knowledge base to various formats
 */

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

export interface ExportOptions {
  format: 'json' | 'markdown' | 'csv'
  outputPath?: string
  category?: 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: ExportOptions, context: any): Promise<string> {
  const { format, outputPath, category } = args

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

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

    if (category) {
      knowledge = knowledge.filter(entry => entry.category === category)
    }

    let content: string
    let defaultPath: string

    switch (format) {
      case 'json':
        content = JSON.stringify(knowledge, null, 2)
        defaultPath = join(homedir(), 'knowledge-export.json')
        break

      case 'markdown':
        content = exportAsMarkdown(knowledge)
        defaultPath = join(homedir(), 'knowledge-export.md')
        break

      case 'csv':
        content = exportAsCSV(knowledge)
        defaultPath = join(homedir(), 'knowledge-export.csv')
        break

      default:
        throw new Error(`Unknown format: ${format}`)
    }

    const output = outputPath || defaultPath
    writeFileSync(output, content, 'utf-8')

    return `✓ Exported ${knowledge.length} entries to ${output}`
  } catch (error: any) {
    throw new Error(`Failed to export knowledge: ${error.message}`)
  }
}

function exportAsMarkdown(entries: KnowledgeEntry[]): string {
  const lines: string[] = ['# Knowledge Base Export', '', `Generated: ${new Date().toISOString()}`, '']

  for (const entry of entries) {
    lines.push(`## ${entry.title || 'Untitled'}`)
    lines.push(`**ID:** ${entry.id}`)
    lines.push(`**Category:** ${entry.category}`)
    lines.push(`**Tags:** ${entry.tags.join(', ') || 'none'}`)
    lines.push(`**Date:** ${new Date(entry.timestamp).toLocaleString()}`)
    if (entry.source) {
      lines.push(`**Source:** ${entry.source}`)
    }
    lines.push('')
    lines.push(entry.content)
    lines.push('')
    lines.push('---')
    lines.push('')
  }

  return lines.join('\n')
}

function exportAsCSV(entries: KnowledgeEntry[]): string {
  const headers = ['ID', 'Title', 'Category', 'Tags', 'Content', 'Source', 'Date']
  const rows = entries.map(entry => [
    entry.id,
    entry.title || '',
    entry.category,
    entry.tags.join('; '),
    `"${entry.content.replace(/"/g, '""')}"`,
    entry.source || '',
    entry.timestamp
  ])

  return [
    headers.join(','),
    ...rows.map(row => row.join(','))
  ].join('\n')
}

export default { handle }
