import {
  CliUsageError,
  RuntimeApiError,
  csv,
  desktopSwitchApplyReason,
  printData,
  rejectArgs,
  runCliAction,
  runtimeRequest,
  summaryLines,
  takeBooleanOption,
  takeFlag,
  takeIntegerOption,
  takeOption,
  type RuntimeApiDeps,
} from "./runtime-api";

interface WebSearchModelOption {
  value: string;
  model: string;
  backend: "openai" | "anthropic";
  authSlot?: boolean;
}

const USAGE = `Usage:
  ocx agent [status] [--json]
  ocx agent injection <status|set> [--model <id|->] [--effort <level|->]
      [--prompt <text|->] [--guidance <on|off>] [--sync-codex-defaults <on|off>] [--json]
  ocx agent injection suggest <work description> [--model <id>] [--apply] [--json]
  ocx agent effort <status|set> [--main <level|->] [--subagent <level|->] [--json]
  ocx agent subagents <status|set|clear> [model,model...] [--json]
  ocx agent subagents force <model|-> [--json]
  ocx agent fallback <status|set|clear> [model,model...] [--poll-ms <5000-600000>] [--json]
  ocx agent roles [status|set <role> <model> [--effort <level>]|suggest [--model <id>] [--apply]] [--json]
  ocx agent sidecar <status|web|vision> [--list] [--model <id|->]
      [--backend web:<openai|anthropic|xai|gemini|exa|-> vision:<openai|anthropic|routed|->]
      [--reasoning <level>] [--max-descriptions <n> (vision)] [--enabled <on|off>]
      [--stream-routed-output <on|off> (web)] [--timeout-ms <1-2147483647> (vision)] [--json]
  ocx agent memory-models <show|set|clear> [options] [--json]
  ocx agent compaction-routing <show|set|clear> [options] [--json]
  ocx agent request-user-input [on|off] [--json]`;

function clearable(value: string | undefined): string | null | undefined {
  return value === "-" ? null : value;
}

async function status(argv: string[], deps: RuntimeApiDeps): Promise<void> {
  const args = [...argv];
  const wantsJson = takeFlag(args, "--json");
  rejectArgs(args, USAGE);
  const [v2, injection, caps, subagents, fallback, sidecars] = await Promise.all([
    runtimeRequest("/api/v2", {}, deps),
    runtimeRequest("/api/injection-model", {}, deps),
    runtimeRequest("/api/effort-caps", {}, deps),
    runtimeRequest("/api/subagent-models", {}, deps),
    runtimeRequest("/api/subagent-model-fallback", {}, deps),
    runtimeRequest("/api/sidecar-settings", {}, deps),
  ]);
  const result = { v2, injection, caps, subagents, fallback, sidecars };
  printData(result, wantsJson, summaryLines(result));
}

interface DelegationProposal {
  model: string | null;
  effort: string | null;
  status: "proposed" | "unassigned" | "unsized";
  tier?: string;
  effortIntent?: string;
  rationale?: string;
  moveUpIf?: string;
  moveDownIf?: string;
  proposedModel?: string | null;
  proposedEffort?: string | null;
  reason?: string | null;
}

async function suggestInjection(args: string[], wantsJson: boolean, deps: RuntimeApiDeps): Promise<void> {
  const model = takeOption(args, "--model");
  const apply = takeFlag(args, "--apply");
  if (args.some(arg => arg.startsWith("--"))) rejectArgs(args, USAGE);
  const work = args.join(" ").trim();
  if (!work) throw new CliUsageError("describe the delegated work to size", USAGE);
  const result = await runtimeRequest<{ sizingModel?: string; proposal?: DelegationProposal }>(
    "/api/injection-model/suggest",
    { method: "POST", body: JSON.stringify({ work, ...(model ? { model } : {}) }) },
    deps,
  );
  const p = result.proposal;
  const alreadySet = p?.status === "proposed" && !!p.proposedModel
    && p.proposedModel === p.model && (p.proposedEffort ?? null) === (p.effort ?? null);
  let applied: { model: string; effort: string | null } | null = null;
  if (apply && !alreadySet && p?.status === "proposed" && p.proposedModel) {
    applied = { model: p.proposedModel, effort: p.proposedEffort ?? null };
    await runtimeRequest("/api/injection-model", { method: "PUT", body: JSON.stringify(applied) }, deps);
  }
  printData(apply ? { ...result, applied, alreadySet } : result, wantsJson, [
    `Sized with ${result.sizingModel ?? "unknown"}.`,
    !p || p.status === "unsized"
      ? `Not sized (${p?.reason ?? "unknown"}).`
      : p.status === "unassigned"
        ? `${p.tier}/${p.effortIntent}, no model (${p.reason ?? "unknown"})`
        : `${p.model ?? "(none)"}${p.effort ? ` (${p.effort})` : ""} -> ${p.proposedModel}${p.proposedEffort ? ` (${p.proposedEffort})` : ""} [${p.tier}/${p.effortIntent}] ${p.rationale ?? ""}`,
    ...(p?.moveUpIf ? [`Move up if: ${p.moveUpIf}`] : []),
    ...(p?.moveDownIf ? [`Move down if: ${p.moveDownIf}`] : []),
    apply
      ? (applied
        ? "Applied to the delegation model."
        : alreadySet
          ? `Already set to ${p!.proposedModel}${p!.proposedEffort ? ` (${p!.proposedEffort})` : ""}; nothing applied.`
          : "Nothing to apply.")
      : "Nothing was written; rerun with --apply to set the delegation model.",
  ]);
}

async function injection(argv: string[], deps: RuntimeApiDeps): Promise<void> {
  const args = [...argv];
  const action = (args.shift() ?? "status").toLowerCase();
  const wantsJson = takeFlag(args, "--json");
  if (action === "status") {
    rejectArgs(args, USAGE);
    const result = await runtimeRequest("/api/injection-model", {}, deps);
    printData(result, wantsJson, summaryLines(result));
    return;
  }
  if (action === "suggest") {
    await suggestInjection(args, wantsJson, deps);
    return;
  }
  if (action !== "set") throw new CliUsageError(`unknown injection action ${action}`, USAGE);
  const model = clearable(takeOption(args, "--model"));
  const effort = clearable(takeOption(args, "--effort"));
  const prompt = clearable(takeOption(args, "--prompt"));
  const guidance = takeBooleanOption(args, "--guidance");
  rejectArgs(args, USAGE);
  const body: Record<string, unknown> = {};
  if (model !== undefined) body.model = model;
  if (effort !== undefined) body.effort = effort;
  if (prompt !== undefined) body.prompt = prompt;
  if (guidance !== undefined) body.multiAgentGuidanceEnabled = guidance;
  if (Object.keys(body).length === 0) throw new CliUsageError("at least one injection option is required", USAGE);
  const result = await runtimeRequest("/api/injection-model", { method: "PUT", body: JSON.stringify(body) }, deps);
  printData(result, wantsJson, ["Agent injection settings updated."]);
}

async function effort(argv: string[], deps: RuntimeApiDeps): Promise<void> {
  const args = [...argv];
  const action = (args.shift() ?? "status").toLowerCase();
  const wantsJson = takeFlag(args, "--json");
  if (action === "status") {
    rejectArgs(args, USAGE);
    const result = await runtimeRequest("/api/effort-caps", {}, deps);
    printData(result, wantsJson, summaryLines(result));
    return;
  }
  if (action !== "set") throw new CliUsageError(`unknown effort action ${action}`, USAGE);
  const main = clearable(takeOption(args, "--main"));
  const subagent = clearable(takeOption(args, "--subagent"));
  rejectArgs(args, USAGE);
  const body: Record<string, unknown> = {};
  if (main !== undefined) body.effortCap = main;
  if (subagent !== undefined) body.subagentEffortCap = subagent;
  if (Object.keys(body).length === 0) throw new CliUsageError("--main and/or --subagent is required", USAGE);
  const result = await runtimeRequest("/api/effort-caps", { method: "PUT", body: JSON.stringify(body) }, deps);
  printData(result, wantsJson, ["Agent effort caps updated."]);
}

async function subagents(argv: string[], deps: RuntimeApiDeps): Promise<void> {
  const args = [...argv];
  const action = (args.shift() ?? "status").toLowerCase();
  const wantsJson = takeFlag(args, "--json");
  if (action === "status") {
    rejectArgs(args, USAGE);
    const result = await runtimeRequest("/api/subagent-models", {}, deps);
    printData(result, wantsJson, summaryLines(result));
    return;
  }
  if (action === "force") {
    const model = args.shift();
    if (!model?.trim()) throw new CliUsageError("a force model or - is required", USAGE);
    rejectArgs(args, USAGE);
    const force = clearable(model);
    const result = await runtimeRequest("/api/subagent-models", { method: "PUT", body: JSON.stringify({ force }) }, deps);
    printData(result, wantsJson, [force ? `Claude subagent force: ${force}. Applies on the next routed ocx claude launch.` : "Claude subagent force cleared."]);
    return;
  }
  let models: string[];
  if (action === "clear") models = [];
  else if (action === "set") {
    const raw = args.shift();
    if (!raw) throw new CliUsageError("comma-separated subagent models are required", USAGE);
    models = csv(raw) ?? [];
  } else throw new CliUsageError(`unknown subagents action ${action}`, USAGE);
  rejectArgs(args, USAGE);
  if (models.length > 5) throw new CliUsageError("at most 5 subagent models are allowed", USAGE);
  const result = await runtimeRequest("/api/subagent-models", { method: "PUT", body: JSON.stringify({ models }) }, deps);
  printData(result, wantsJson, [`Subagent roster: ${models.join(", ") || "cleared"}`]);
}

async function fallback(argv: string[], deps: RuntimeApiDeps): Promise<void> {
  const args = [...argv];
  const action = (args.shift() ?? "status").toLowerCase();
  const wantsJson = takeFlag(args, "--json");
  if (action === "status") {
    rejectArgs(args, USAGE);
    const result = await runtimeRequest("/api/subagent-model-fallback", {}, deps);
    printData(result, wantsJson, summaryLines(result));
    return;
  }
  const body: Record<string, unknown> = {};
  if (action === "clear") body.models = [];
  else if (action === "set") {
    const raw = args[0] && !args[0].startsWith("--") ? args.shift() : undefined;
    if (raw) body.models = csv(raw) ?? [];
  } else throw new CliUsageError(`unknown fallback action ${action}`, USAGE);
  const pollMs = takeIntegerOption(args, "--poll-ms", { min: 5_000 });
  if (pollMs !== undefined) {
    if (pollMs > 600_000) throw new CliUsageError("--poll-ms must be <= 600000", USAGE);
    body.pollMs = pollMs;
  }
  rejectArgs(args, USAGE);
  if (Object.keys(body).length === 0) throw new CliUsageError("models and/or --poll-ms is required", USAGE);
  const result = await runtimeRequest("/api/subagent-model-fallback", { method: "PUT", body: JSON.stringify(body) }, deps);
  printData(result, wantsJson, ["Subagent fallback settings updated."]);
}

async function sidecar(argv: string[], deps: RuntimeApiDeps): Promise<void> {
  const args = [...argv];
  const section = (args.shift() ?? "status").toLowerCase();
  const wantsJson = takeFlag(args, "--json");
  if (section === "status") {
    rejectArgs(args, USAGE);
    const result = await runtimeRequest("/api/sidecar-settings", {}, deps);
    printData(result, wantsJson, summaryLines(result));
    return;
  }
  if (section !== "web" && section !== "vision") throw new CliUsageError("sidecar must be web, vision, or status", USAGE);
  // --list must be consumed BEFORE rejectArgs sees it. It prints the server's
  // candidate set — the exact list the GUI picker shows (#2188): the server
  // computes it once and every surface consumes it, so the CLI cannot drift.
  const wantsList = takeFlag(args, "--list");
  if (wantsList) {
    rejectArgs(args, USAGE);
    const settings = await runtimeRequest("/api/sidecar-settings", {}, deps) as {
      webSearchModels?: WebSearchModelOption[];
      visionModels?: Array<{ value: string; backend?: string; baseline?: boolean }>;
    };
    if (section === "web") {
      const options = settings.webSearchModels ?? [];
      printData(options, wantsJson, options.length === 0
        ? ["no runnable web-search sidecar models (log in to ChatGPT or Anthropic)"]
        : options.map(option => `${option.value} [${option.backend}]${option.authSlot ? " (auth slot)" : ""}`));
    } else {
      const options = settings.visionModels ?? [];
      printData(options, wantsJson, options.length === 0
        ? ["no eligible vision describers"]
        : options.map(option => `${option.value}${option.backend ? ` [${option.backend}]` : ""}${option.baseline ? " (baseline)" : ""}`));
    }
    return;
  }
  const model = takeOption(args, "--model");
  const backend = takeOption(args, "--backend");
  const reasoning = takeOption(args, "--reasoning");
  const maxDescriptionsPerTurn = takeIntegerOption(args, "--max-descriptions", { min: 1 });
  if (section === "web" && maxDescriptionsPerTurn !== undefined) throw new CliUsageError("--max-descriptions applies only to the vision sidecar", USAGE);
  const enabled = takeBooleanOption(args, "--enabled");
  rejectArgs(args, USAGE);
  const settings: Record<string, unknown> = {};
  if (model !== undefined) settings.model = model === "-" ? "" : model;
  if (backend !== undefined) settings.backend = backend === "-" ? null : backend;
  if (reasoning !== undefined) settings.reasoning = reasoning;
  if (maxDescriptionsPerTurn !== undefined) settings.maxDescriptionsPerTurn = maxDescriptionsPerTurn;
  if (enabled !== undefined) settings.enabled = enabled;
  if (Object.keys(settings).length === 0) throw new CliUsageError("at least one sidecar option is required", USAGE);
  if (section === "web" && model !== undefined && model !== "-") {
    const offered = await runtimeRequest("/api/sidecar-settings", {}, deps) as {
      webSearchModels?: WebSearchModelOption[];
    };
    const requestedBackend = backend === "-" ? "openai" : backend;
    const option = offered.webSearchModels?.find(candidate =>
      (candidate.value === model || candidate.model === model)
      && (requestedBackend === undefined || candidate.backend === requestedBackend));
    if (option) {
      settings.model = option.model;
      if (backend !== "-") settings.backend = option.backend;
    }
  }
  const body = section === "web" ? { webSearch: settings } : { vision: settings };
  const result = await runtimeRequest("/api/sidecar-settings", { method: "PUT", body: JSON.stringify(body) }, deps);
  const lines = [`${section} sidecar settings updated.`];
  // Only a switch that MOVED owes a Codex-side write, and only the server can say whether that
  // write happened — silence here would read as "the native tool is off now" either way. The
  // wording is the Desktop switches' one vocabulary for the same report.
  const apply = (result as { codexWebSearch?: { applied?: boolean; reason?: string; detail?: string } } | null)?.codexWebSearch;
  if (apply && apply.reason !== "not_requested") {
    const detail = typeof apply.detail === "string" && apply.detail.length > 0 ? ` Details: ${apply.detail}` : "";
    // `ocx sync` re-runs the same injection the external provider owns — the retry
    // advice is meaningless on that outcome, same as the Desktop-switch report.
    const retry = apply.reason === "external_provider"
      ? ""
      : apply.reason === "ownership_undetermined"
      ? " Resolve the reported config.toml read error, then inspect 'ocx system settings --json'."
      : apply.reason === "integration_disabled"
      ? " Enable Codex integration before applying the stored settings."
      : " Run 'ocx sync' to apply the stored settings.";
    lines.push(apply.applied === true
      ? "Codex config: ~/.codex/config.toml was rewritten."
      : `Codex config: ~/.codex/config.toml was not rewritten because ${desktopSwitchApplyReason(apply.reason)}.${detail}${retry}`);
  }
  printData(result, wantsJson, lines);
}

interface CodexAgentRolesStatus {
  lazycodex?: { detected?: boolean };
  omoJsonc?: { state?: string } | null;
  roles?: Array<{ role: string; model: string | null; effort?: string | null; omoJsoncModel: string | null }>;
}

interface CodexRoleProposal {
  role: string;
  model: string | null;
  effort?: string | null;
  status: "proposed" | "unassigned" | "unsized";
  tier?: string;
  effortIntent?: string;
  rationale?: string;
  proposedModel?: string | null;
  proposedEffort?: string | null;
  reason?: string | null;
}

function proposalAlreadySet(proposal: CodexRoleProposal): boolean {
  return proposal.proposedModel === proposal.model
    && (proposal.proposedEffort == null || proposal.proposedEffort === proposal.effort);
}

const OMO_JSONC_NOT_WRITTEN = new Set(["skipped_comments", "invalid", "write_failed"]);

async function suggestRoles(args: string[], wantsJson: boolean, deps: RuntimeApiDeps): Promise<void> {
  const model = takeOption(args, "--model");
  const apply = takeFlag(args, "--apply");
  rejectArgs(args, USAGE);
  const result = await runtimeRequest<{ sizingModel?: string; proposals?: CodexRoleProposal[] }>(
    "/api/codex-agent-roles/auto-assign",
    { method: "POST", body: JSON.stringify(model ? { model } : {}) },
    deps,
  );
  const proposals = result.proposals ?? [];
  const applied: Array<{ role: string; model: string; effort?: string }> = [];
  const skipped = apply ? proposals.filter(p => p.status === "proposed" && p.proposedModel && proposalAlreadySet(p)).map(p => p.role) : [];
  const changes = proposals.filter((p): p is CodexRoleProposal & { proposedModel: string } =>
    p.status === "proposed" && !!p.proposedModel && !proposalAlreadySet(p));
  const { ROLE_HISTORY_LIMIT } = await import("../codex/role-model-history");
  const omoJsoncNotWritten: Array<{ role: string; status: string }> = [];
  let batch: string | undefined;
  let failure: { cause: unknown; unconfirmedRole: string; unattemptedRoles: string[] } | undefined;
  if (apply) {
    // Splitting into several batches would hide earlier changes from the bounded Restore list.
    if (changes.length > ROLE_HISTORY_LIMIT) {
      const message = `${changes.length} changed proposals exceed the ${ROLE_HISTORY_LIMIT}-role batch limit. No role files were written. Preview without --apply and use 'ocx agent roles set' for individual changes.`;
      printData({ ...result, applied, skipped, omoJsoncNotWritten, complete: false,
        refusal: { code: "too_many_role_changes", limit: ROLE_HISTORY_LIMIT, count: changes.length },
        unattemptedRoles: changes.map(p => p.role) }, wantsJson, [message]);
      throw new RuntimeApiError(message, 409, null);
    }
    for (const [index, proposal] of changes.entries()) {
      const body = {
        model: proposal.proposedModel,
        ...(proposal.proposedEffort ? { effort: proposal.proposedEffort } : {}),
        ...(batch ? { batch } : {}),
      };
      let written: { batch?: string; omoJsonc?: { status?: string } } | null;
      try {
        written = await runtimeRequest<typeof written>(
          `/api/codex-agent-roles/${encodeURIComponent(proposal.role)}`,
          { method: "PUT", body: JSON.stringify(body) },
          deps,
        );
      } catch (cause) {
        // A lost response can follow a persisted write: report uncertainty and do not replay it.
        failure = { cause, unconfirmedRole: proposal.role, unattemptedRoles: changes.slice(index + 1).map(p => p.role) };
        break;
      }
      batch = written?.batch ?? batch;
      applied.push({ role: proposal.role, model: body.model, ...(proposal.proposedEffort ? { effort: proposal.proposedEffort } : {}) });
      const omoStatus = written?.omoJsonc?.status;
      if (omoStatus && OMO_JSONC_NOT_WRITTEN.has(omoStatus)) omoJsoncNotWritten.push({ role: proposal.role, status: omoStatus });
    }
  }
  printData(apply ? { ...result, applied, skipped, omoJsoncNotWritten, ...(batch ? { batch } : {}),
    ...(failure ? { complete: false, unconfirmedRole: failure.unconfirmedRole, unattemptedRoles: failure.unattemptedRoles } : {}) } : result, wantsJson, [
    `Sized with ${result.sizingModel ?? "unknown"}.`,
    ...proposals.map(p => p.status === "unsized"
      ? `${p.role}: not sized (${p.reason ?? "unknown"})`
      : p.status === "unassigned"
        ? `${p.role}: ${p.tier}/${p.effortIntent}, no model (${p.reason ?? "unknown"})`
        : `${p.role}: ${p.model ?? "(no pin)"} -> ${p.proposedModel}${p.proposedEffort ? ` (${p.proposedEffort})` : ""} [${p.tier}/${p.effortIntent}] ${p.rationale ?? ""}`),
    apply
      ? `Applied ${applied.length} of ${proposals.length} roles.${skipped.length > 0 ? ` Skipped ${skipped.length} already set: ${skipped.join(", ")}.` : ""}`
      : `Nothing was written; --apply accepts up to ${ROLE_HISTORY_LIMIT} changed roles in one batch. Use 'ocx agent roles set' for individual changes.`,
    ...omoJsoncNotWritten.map(entry => `${entry.role}: omo.jsonc not written (${entry.status}); the role TOML was updated.`),
    ...(batch ? [`Recorded history batch: ${batch}. Restore uses the retained changes in the dashboard's Change history.`] : []),
    ...(failure ? [
      `Confirmed writes: ${applied.map(p => p.role).join(", ") || "none"}.`,
      `Write not confirmed for ${failure.unconfirmedRole}; it may have been saved. Not attempted: ${failure.unattemptedRoles.join(", ") || "none"}.`,
      "Earlier writes remain applied. Inspect 'ocx agent roles --json' before retrying.",
    ] : []),
  ]);
  if (failure) throw failure.cause;
}

async function roles(argv: string[], deps: RuntimeApiDeps): Promise<void> {
  const args = [...argv];
  const wantsJson = takeFlag(args, "--json");
  const action = (args.shift() ?? "status").toLowerCase();
  if (action === "status") {
    rejectArgs(args, USAGE);
    const result = await runtimeRequest<CodexAgentRolesStatus>("/api/codex-agent-roles", {}, deps);
    if (result.lazycodex?.detected !== true) {
      printData(result, wantsJson, ["omo (Codex / LazyCodex) is not installed in this CODEX_HOME; role models are managed only with it."]);
      return;
    }
    const rows = result.roles ?? [];
    printData(result, wantsJson, [
      "omo (Codex / LazyCodex): detected",
      ...(rows.length === 0 ? ["No Codex agent roles found."] : rows.map(row => `${row.role}: ${row.model ?? "(no model pin)"}${row.effort ? ` (${row.effort})` : ""}`)),
      `omo.jsonc: ${result.omoJsonc?.state ?? "unknown"}`,
    ]);
    return;
  }
  if (action === "suggest") {
    await suggestRoles(args, wantsJson, deps);
    return;
  }
  if (action !== "set") throw new CliUsageError(`unknown roles action ${action}`, USAGE);
  const effort = takeOption(args, "--effort");
  // An empty value is a supplied flag, not an absent one: dropping it would change the model and
  // silently ignore the effort the operator asked for.
  if (effort !== undefined && effort.trim() === "") throw new CliUsageError("--effort needs a reasoning level", USAGE);
  const role = args.shift();
  const model = args.shift();
  if (!role || !model) throw new CliUsageError("a role and a model are required", USAGE);
  rejectArgs(args, USAGE);
  const result = await runtimeRequest<{ toml?: { status?: string }; omoJsonc?: { status?: string } }>(
    `/api/codex-agent-roles/${encodeURIComponent(role)}`,
    { method: "PUT", body: JSON.stringify(effort !== undefined ? { model, effort } : { model }) },
    deps,
  );
  const omo = result.omoJsonc?.status;
  printData(result, wantsJson, [
    `${role}: ${model}${effort ? ` (${effort})` : ""} (role TOML ${result.toml?.status ?? "unknown"})`,
    omo === "skipped_comments"
      ? "omo.jsonc: not written, because it contains comments that a rewrite would lose."
      : `omo.jsonc: ${omo ?? "unknown"}`,
  ]);
}

export async function handleAgentCommand(argv: string[], deps: RuntimeApiDeps = {}): Promise<number> {
  const has = (flag: string) => argv.some(arg => arg === flag || arg.startsWith(`${flag}=`));
  if ((argv[0] === "injection" || argv[0] === "guidance") && has("--sync-codex-defaults")) {
    const { handleInjectionDefaults } = await import("./agent-runtime-settings");
    return handleInjectionDefaults(argv.slice(1), deps);
  }
  if (argv[0] === "sidecar" && (has("--stream-routed-output") || has("--timeout-ms"))) {
    const { handleSidecarRuntimeSettings } = await import("./agent-runtime-settings");
    return handleSidecarRuntimeSettings(argv.slice(1), deps);
  }
  if (argv[0] === "memory-models" || argv[0] === "compaction-routing") {
    const { handleAgentSettingsCommand } = await import("./agent-settings");
    return handleAgentSettingsCommand(argv[0], argv.slice(1), deps);
  }
  return runCliAction(async () => {
    const [sub = "status", ...rest] = argv;
    if (sub === "status") await status(rest, deps);
    else if (sub === "injection" || sub === "guidance") await injection(rest, deps);
    else if (sub === "effort") await effort(rest, deps);
    else if (sub === "subagents" || sub === "roster") await subagents(rest, deps);
    else if (sub === "fallback") await fallback(rest, deps);
    else if (sub === "roles") await roles(rest, deps);
    else if (sub === "sidecar") await sidecar(rest, deps);
    // Lives here rather than as a top-level verb because it is an agent-behavior feature flag:
    // it controls whether default mode may ask the operator a question mid-task.
    else if (sub === "request-user-input") {
      const { requestUserInputAction } = await import("./inspect");
      await requestUserInputAction(rest, deps);
    }
    else throw new CliUsageError(`unknown agent command ${sub}`, USAGE);
  });
}

export const AGENT_USAGE = USAGE;
