/**
 * RunCommand - Run the AirCoding project (spawns TUI)
 * DD §17. Routes side effects through RuntimeApp.
 *
 * @module packages/cli/src/commands/run
 */

import { loadConfig } from '../bootstrap/loadConfig.js'
import { createRuntime } from '../bootstrap/createRuntime.js'
import { TuiApp } from '@aircoding/tui'

export async function runCommand(project_path?: string): Promise<void> {
  const config = loadConfig(project_path)
  console.log(`Starting AirCoding for ${config.project_root || process.cwd()}`)

  const runtime = await createRuntime(config)
  await runtime.start()

  // Wire TUI to runtime's ProjectionClient (B15 fix)
  const tui = new TuiApp({ client: runtime.projection_client })
  await tui.start()

  // Graceful shutdown handler
  process.on('SIGINT', async () => {
    console.log('\nShutting down...')
    tui.stop()
    await runtime.shutdown()
    process.exit(0)
  })
}
