import chalk from 'chalk'
import * as fs from 'fs'
import * as path from 'path'
import * as os from 'os'
import { execSync } from 'child_process'

export async function watchCommand(options: { git?: boolean }) {
  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 = fs.existsSync(configPath) ? JSON.parse(fs.readFileSync(configPath, 'utf-8')) : null

  if (options.git) {
    await installGitHook(config)
  } else {
    // Regular file watcher - import and run existing watcher
    const { startWatcher } = await import('../services/watcher')
    const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'))
    startWatcher(config.rootPath || process.cwd(), 'https://docsync-api.onrender.com')
  }
}

async function installGitHook(config: any) {
  try {
    // Find git root
    const gitRoot = execSync('git rev-parse --show-toplevel').toString().trim()
    const hookPath = path.join(gitRoot, '.git', 'hooks', 'post-commit')
    
    const hookContent = `#!/bin/sh
# DocSync post-commit hook
# Auto-generates documentation for changed files

CHANGED_FILES=$(git diff-tree --no-commit-id -r --name-only HEAD)

for FILE in $CHANGED_FILES; do
  if echo "$FILE" | grep -qE '\\.(ts|js|py|go|rs|java|rb|php|cs|cpp|c|swift|kt)$'; then
    docsync generate "$FILE"
  fi
done
`
    fs.writeFileSync(hookPath, hookContent)
    execSync(`chmod +x ${hookPath}`)
    
    console.log(chalk.green('✅ Git hook installed!'))
    
    // Save to API
    if (config?.token) {
      try {
        await fetch('https://docsync-api.onrender.com/git-hooks/save', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${config.token}` },
          body: JSON.stringify({ repoPath: gitRoot })
        })
      } catch (_) {}
    }
    console.log(chalk.gray('DocSync will now generate docs automatically on every git commit.'))
    console.log(chalk.gray(`Hook installed at: ${hookPath}`))
  } catch (error: any) {
    console.log(chalk.red('Error: Not a git repository or git not found.'))
    console.log(chalk.gray('Run this command from inside a git repository.'))
    process.exit(1)
  }
}
