import type { Config } from '../config/index.js';
import { AgentConfigRegistry, AgentRouter } from '../agents/index.js';
import { DockerSandbox, SandboxManager } from '../sandbox/index.js';
import type { Lifecycle } from './lifecycle.js';

export interface AgentsDeps {
  config: Config;
  lifecycle: Lifecycle;
}

export interface AgentsResult {
  agentConfigRegistry: AgentConfigRegistry;
  agentRouter: AgentRouter;
  sandboxManager?: SandboxManager;
}

export async function initAgents(deps: AgentsDeps): Promise<AgentsResult> {
  const { config, lifecycle } = deps;

  // Initialize agent config registry and router
  const agentConfigRegistry = new AgentConfigRegistry();
  if (config.agent_configs && Object.keys(config.agent_configs).length > 0) {
    agentConfigRegistry.loadFromConfig(config.agent_configs);
    console.log(`Loaded ${Object.keys(config.agent_configs).length} agent config(s)`);
  }
  const agentRouter = new AgentRouter(config.routing);

  // Initialize sandbox manager if Docker is available
  let sandboxManager: SandboxManager | undefined;
  if (config.sandbox.enabled) {
    const dockerAvailable = await DockerSandbox.isAvailable();
    if (dockerAvailable) {
      sandboxManager = new SandboxManager(config.sandbox);
      console.log(`Docker sandbox enabled (image=${config.sandbox.image}, network=${config.sandbox.network})`);
    } else {
      console.warn('Docker sandbox enabled but Docker not available — falling back to host execution');
    }
  }

  if (sandboxManager) {
    lifecycle.onShutdown(async () => {
      await sandboxManager!.destroyAll();
      console.log('Docker sandboxes destroyed');
    });
  }

  return { agentConfigRegistry, agentRouter, sandboxManager };
}
