/**
 * RuntimeApp - Main application entry point
 * DD §22.2. Wires all subsystems respecting dependency direction.
 *
 * @module packages/runtime/src/app/RuntimeApp
 */

import type { SessionID, ProjectID } from '@aircoding/contracts'

import { Scheduler } from '../scheduler/Scheduler.js'
import { WorkerManager } from '../workers/WorkerManager.js'
import { ContextAssembler } from '../context/ContextAssembler.js'
import { DoctorService } from '../doctor/DoctorService.js'
import { ProjectionStore } from '../projection/ProjectionStore.js'
import { Logger } from '../logging/Logger.js'
import { join } from 'path'

export interface RuntimeAppConfig {
  project_root: string
  session_id: SessionID
  project_id: ProjectID
  log_dir?: string
}

export class RuntimeApp {
  private config: RuntimeAppConfig
  scheduler: Scheduler
  worker_manager: WorkerManager
  context_assembler: ContextAssembler
  doctor: DoctorService
  projection_store: ProjectionStore
  logger: Logger

  constructor(config: RuntimeAppConfig) {
    this.config = config
    this.logger = new Logger(config.log_dir || join(config.project_root, '.air', 'logs'))
    this.scheduler = new Scheduler({
      session_id: config.session_id,
      project_id: config.project_id,
      project_root: config.project_root
    })
    this.worker_manager = new WorkerManager()
    this.context_assembler = new ContextAssembler()
    this.doctor = new DoctorService(config.project_root)
    this.projection_store = new ProjectionStore()
  }

  /**
   * Start the runtime.
   */
  async start(): Promise<void> {
    this.logger.info('RuntimeApp starting', {
      session_id: this.config.session_id,
      project_root: this.config.project_root
    })

    // Run doctor check on startup
    const report = await this.doctor.run_diagnostics('self_bootstrap')
    if (!report.bootstrap_passed) {
      this.logger.fatal('Self-bootstrap failed', { report })
      throw new Error('Runtime bootstrap failed')
    }

    this.logger.info('RuntimeApp started')
  }

  /**
   * Shutdown the runtime.
   */
  async shutdown(): Promise<void> {
    this.logger.info('RuntimeApp shutting down')
    // Flush logs, close DBs, stop workers
    this.logger.info('RuntimeApp stopped')
  }
}

export function createRuntimeApp(config: RuntimeAppConfig): RuntimeApp {
  return new RuntimeApp(config)
}
