import chalk from 'chalk'
import * as fs from 'fs'
import * as path from 'path'
import * as os from 'os'

export async function generateCommand(filePath: string) {
  const configPath = path.join(os.homedir(), '.docsync', 'config.json')
  if (!fs.existsSync(configPath)) {
    console.log(chalk.red('Not configured. Run docsync init first.'))
    process.exit(1)
  }

  const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'))
  const apiUrl = 'https://docsync-api.onrender.com'

  if (!fs.existsSync(filePath)) {
    console.log(chalk.red(`File not found: ${filePath}`))
    process.exit(1)
  }

  const code = fs.readFileSync(filePath, 'utf-8')
  const relativePath = path.relative(process.cwd(), filePath)

  console.log(chalk.yellow(`Generating doc for: ${relativePath}`))

  try {
    const response = await fetch(`${apiUrl}/docs/generate`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${config.token}`
      },
      body: JSON.stringify({
        filePath: relativePath,
        code,
        destination: config.destination,
        projectId: config.projectId,
        notionToken: config.notionToken,
        googleToken: config.googleToken,
        confluenceToken: config.confluenceToken,
        parentPageId: config.parentPageId,
        spaceId: config.spaceId,
        slackWebhookUrl: config.slackWebhookUrl,
        githubToken: config.githubToken,
        githubRepo: config.githubRepo,
        linearToken: config.linearToken,
        linearTeamId: config.linearTeamId,
        readmeApiKey: config.readmeApiKey,
            llmProvider: config.llmProvider,
            llmApiKey: config.llmApiKey
      })
    })

    const data = await response.json()
    if (data.error) {
      console.log(chalk.red(`Error: ${data.error}`))
    } else {
      const quality = data.quality || 7
      const qualityEmoji = quality >= 8 ? '🟢' : quality >= 6 ? '🟡' : '🔴'
      console.log(chalk.green(`✅ Doc generated: ${relativePath}`))
      console.log(chalk.gray(`   ${qualityEmoji} Quality score: ${quality}/10`))
    }
  } catch (error: any) {
    console.log(chalk.red(`Error: ${error.message}`))
  }

  process.exit(0)
}
