/**
 * DoctorCommand - Diagnostic and repair command
 * DD §17. doctor [--fix|--bundle].
 *
 * @module packages/cli/src/commands/doctor
 */

import { loadConfig } from '../bootstrap/loadConfig.js'
import { DoctorService } from '@aircoding/runtime'

export async function doctorCommand(options: { fix?: boolean; bundle?: boolean; scope?: string }): Promise<void> {
  const config = loadConfig()
  const project_root = config.project_root || process.cwd()
  const doctor = new DoctorService(project_root)

  console.log('Running diagnostics...\n')

  const report = await doctor.run_diagnostics(options.scope as any || 'all')

  for (const check of report.checks) {
    const icon = check.passed ? '✅' : '❌'
    const fixable = check.fixable ? ' [fixable]' : ''
    console.log(`  ${icon} ${check.name}: ${check.message}${fixable}`)
  }

  console.log(`\nBootstrap: ${report.bootstrap_passed ? '✅ PASS' : '❌ FAIL'}`)
  console.log(`All checks: ${report.all_passed ? '✅ PASS' : '❌ FAIL'}`)
  console.log(`Fixable:   ${report.fixable_count} issues`)

  if (options.fix) {
    console.log('\nAttempting fixes...')
    for (const check of report.checks) {
      if (!check.passed && check.fixable) {
        const result = await doctor.fix(check.name)
        console.log(`  ${result.ok ? '✅' : '❌'} ${check.name}: ${result.message}`)
      }
    }
  }

  if (options.bundle) {
    console.log('\nBundle feature not yet implemented (P8)')
  }
}
