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

export async function historyCommand(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'

  const url = filePath
    ? `${apiUrl}/history/${config.projectId}?filePath=${encodeURIComponent(filePath)}`
    : `${apiUrl}/history/${config.projectId}`

  const res = await fetch(url, {
    headers: { Authorization: `Bearer ${config.token}` }
  })
  const data = await res.json()

  if (!data.history || data.history.length === 0) {
    console.log(chalk.gray('\nNo history found.\n'))
    process.exit(0)
  }

  console.log(chalk.bold('\n📜 Doc History\n'))

  data.history.forEach((entry: any, i: number) => {
    const date = new Date(entry.created_at).toLocaleString()
    console.log(`${chalk.cyan(`#${i + 1}`)} ${chalk.white(entry.file_path)} ${chalk.gray(`→ ${entry.destination}`)}`)
    console.log(`   ${chalk.gray(date)}`)
    console.log(`   ${chalk.gray(entry.content.slice(0, 100).replace(/\n/g, ' '))}...`)
    console.log()
  })

  process.exit(0)
}
