'use strict';

const { createUnavailableResult } = require('./contract');
const multiAgent = require('./multi-agent');

const RUNNERS = new Map();

function registerAgentRunner(runner) {
  if (!runner || !runner.id || typeof runner.runTask !== 'function') {
    throw new Error('Invalid agent runner');
  }
  RUNNERS.set(runner.id, runner);
  return runner;
}

function getAgentRunner(id = 'claude-code') {
  return RUNNERS.get(id) || null;
}

function listAgentRunners() {
  return [...RUNNERS.values()].map(runner => ({
    id: runner.id,
    providerType: runner.providerType,
    kind: runner.kind || 'cli-agent',
    capabilities: runner.capabilities || {},
  }));
}

function listAgentHarnesses() {
  return [...RUNNERS.values()].map(runner => ({
    id: runner.id,
    runnerId: runner.id,
    providerType: runner.providerType,
    kind: runner.kind || 'cli-agent',
    priority: Number.isFinite(Number(runner.priority)) ? Number(runner.priority) : 0,
    capabilities: {
      modes: runner.capabilities?.modes || ['plan', 'build', 'review', 'analysis'],
      persistentSessions: Boolean(runner.capabilities?.resume),
      streaming: Boolean(runner.capabilities?.streamJson),
      codeEditing: true,
      reviewOnly: false,
      sandboxModes: runner.capabilities?.sandboxModes || [],
      supportsImages: Boolean(runner.capabilities?.images),
      supportsPatch: runner.capabilities?.patch !== false,
      ...(runner.capabilities || {}),
    },
  }));
}

async function runAgentTask(runnerId, options = {}) {
  const id = runnerId || 'claude-code';
  const runner = getAgentRunner(id);
  if (!runner) {
    return createUnavailableResult({
      runnerId: id,
      providerType: 'unknown',
      mode: options.mode,
      sessionId: options.sessionId,
      error: `Unknown agent runner: ${id}`,
    });
  }
  return runner.runTask(options);
}

function runControlledMultiAgent(assignments, opts = {}) {
  return multiAgent.runControlledMultiAgent(assignments, {
    ...opts,
    runTask: opts.runTask || runAgentTask,
  });
}

registerAgentRunner(require('./claude-code'));
registerAgentRunner(require('./codex'));
registerAgentRunner(require('./gemini'));

module.exports = {
  ...multiAgent,
  registerAgentRunner,
  getAgentRunner,
  listAgentRunners,
  listAgentHarnesses,
  runAgentTask,
  runControlledMultiAgent,
};
