/**
 * ServiceRegistry - Dependency injection container
 * DD §22.2. Wires all subsystems respecting dependency direction.
 *
 * @module packages/runtime/src/app/ServiceRegistry
 */

import { DatabaseManager } from '../storage/DatabaseManager.js'
import { PermissionEngine } from '../security/PermissionEngine.js'
import { ToolRegistry } from '../tools/ToolRegistry.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 { Scheduler } from '../scheduler/Scheduler.js'
import { WorkerManager } from '../workers/WorkerManager.js'

export interface ServiceGraph {
  database: DatabaseManager
  permission_engine: PermissionEngine
  tool_registry: ToolRegistry
  context_assembler: ContextAssembler
  doctor: DoctorService
  projection_store: ProjectionStore
  logger: Logger
  scheduler: Scheduler | null
  worker_manager: WorkerManager
}

export class ServiceRegistry {
  private services: Map<string, unknown> = new Map()

  /**
   * Register all services for a project.
   */
  build(project_root: string, session_id: string, project_id: string): ServiceGraph {
    const logger = new Logger(`${project_root}/.air/logs`)
    const database = new DatabaseManager(`${project_root}/.air/sessions/${session_id}.db`)
    const permission_engine = new PermissionEngine(project_root)
    const tool_registry = new ToolRegistry(project_root)
    const context_assembler = new ContextAssembler()
    const doctor = new DoctorService(project_root)
    const projection_store = new ProjectionStore()
    const worker_manager = new WorkerManager()
    const scheduler = new Scheduler({ session_id, project_id, project_root })

    // Register all services
    this.services.set('database', database)
    this.services.set('permission_engine', permission_engine)
    this.services.set('tool_registry', tool_registry)
    this.services.set('context_assembler', context_assembler)
    this.services.set('doctor', doctor)
    this.services.set('projection_store', projection_store)
    this.services.set('logger', logger)
    this.services.set('scheduler', scheduler)
    this.services.set('worker_manager', worker_manager)

    return {
      database, permission_engine, tool_registry,
      context_assembler, doctor, projection_store,
      logger, scheduler, worker_manager
    }
  }

  /**
   * Get a registered service.
   */
  get<T>(name: string): T | undefined {
    return this.services.get(name) as T | undefined
  }

  /**
   * Check all services are healthy.
   */
  health_check(): Record<string, boolean> {
    const results: Record<string, boolean> = {}
    for (const [name, _service] of this.services) {
      results[name] = true // Would do actual health check
    }
    return results
  }
}
