/**
 * InitCommand - First-run project initialization wizard
 * DD §17.
 *
 * @module packages/cli/src/commands/init
 */

import { mkdirSync, writeFileSync, existsSync } from 'fs'
import { join } from 'path'
import { randomUUID } from 'crypto'
import { loadConfig } from '../bootstrap/loadConfig.js'

export async function initCommand(project_path?: string): Promise<void> {
  // TODO(P8): Route filesystem writes through RuntimeApp→ToolRegistry→PermissionEngine (INV-3).
  const project_root = project_path || process.cwd()
  console.log(`Initializing AirCoding project at ${project_root}`)

  // Create .air directory structure
  const dirs = [
    join(project_root, '.air', 'shared'),
    join(project_root, '.air', 'local'),
    join(project_root, '.air', 'sessions'),
    join(project_root, '.air', 'logs'),
    join(project_root, '.air', 'workspaces')
  ]

  for (const dir of dirs) {
    if (!existsSync(dir)) {
      mkdirSync(dir, { recursive: true })
      console.log(`  Created ${dir}`)
    }
  }

  // Generate project_id
  const project_id = `proj_${randomUUID()}`

  // Write project.json
  const project_json = {
    project_id,
    name: project_root.split('/').pop() || 'aircoding-project',
    created_at: new Date().toISOString(),
    version: '1.0.0-alpha'
  }

  writeFileSync(
    join(project_root, '.air', 'shared', 'project.json'),
    JSON.stringify(project_json, null, 2)
  )
  console.log(`  Created .air/shared/project.json (project_id: ${project_id})`)

  // Write default rules
  writeFileSync(
    join(project_root, '.air', 'shared', 'rules.md'),
    '# Project Rules\n\nAdd your project-specific rules here.\n'
  )

  console.log('\nProject initialized successfully!')
  console.log(`Run 'air run' to start a session.`)
}
