'use strict';

class AgentRuntimeRegistry {
  constructor() {
    this.runtimes = new Map();
  }

  registerRuntime(runtime) {
    if (!runtime || !runtime.id || typeof runtime.run !== 'function') {
      throw new Error('Invalid agent runtime');
    }
    this.runtimes.set(runtime.id, runtime);
    return runtime;
  }

  getRuntime(id = 'cli-agent') {
    return this.runtimes.get(id) || null;
  }

  listRuntimes() {
    return [...this.runtimes.values()].map((runtime) => ({
      id: runtime.id,
      kind: runtime.kind || runtime.id,
      capabilities: runtime.capabilities || {},
    }));
  }

  clear() {
    this.runtimes.clear();
  }
}

function createDefaultRuntimeRegistry({ runTask } = {}) {
  const registry = new AgentRuntimeRegistry();
  registry.registerRuntime({
    id: 'cli-agent',
    kind: 'cli-agent',
    capabilities: {
      oneshot: true,
      persistentSessions: false,
      streaming: false,
    },
    run: async (request) => {
      const runner = runTask || lazyRunAgentTask();
      return runner(request.runnerId, {
        prompt: request.task || request.prompt || '',
        cwd: request.cwd,
        timeoutMs: request.timeoutMs,
        model: request.model,
        mode: request.mode,
        sessionId: request.sessionId,
        writeScope: request.writeScope,
        sandbox: request.sandbox,
      });
    },
  });
  return registry;
}

function lazyRunAgentTask() {
  return require('../agent-runners').runAgentTask;
}

module.exports = {
  AgentRuntimeRegistry,
  createDefaultRuntimeRegistry,
};
