/**
 * loadConfig - Load configuration for the AirCoding CLI
 * DD §22.2. Loads global + project config.
 *
 * @module packages/cli/src/bootstrap/loadConfig
 */

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

export interface AirConfig {
  project_root?: string
  provider: string
  model: string
  api_key?: string
  base_url?: string
  log_level: string
  max_concurrency: number
  token_budget: number
}

const DEFAULT_CONFIG: AirConfig = {
  provider: 'anthropic',
  model: 'claude-sonnet-4-6',
  log_level: 'info',
  max_concurrency: 4,
  token_budget: 200000
}

export function loadConfig(project_root?: string): AirConfig {
  let config = { ...DEFAULT_CONFIG }

  // Load global config: ~/.air/config.json
  const global_path = join(homedir(), '.air', 'config.json')
  if (existsSync(global_path)) {
    try {
      const global = JSON.parse(readFileSync(global_path, 'utf-8'))
      config = { ...config, ...global }
    } catch {
      // Ignore malformed global config
    }
  }

  // Load project config: .air/local/config.json
  if (project_root) {
    const project_path = join(project_root, '.air', 'local', 'config.json')
    if (existsSync(project_path)) {
      try {
        const project = JSON.parse(readFileSync(project_path, 'utf-8'))
        config = { ...config, ...project }
      } catch {
        // Ignore malformed project config
      }
    }
    config.project_root = project_root
  }

  return config
}
