/**
 * DCS Task + AskUserQuestion tools for Pi.
 *
 * The DCS workflows and skill shims are written against two Claude Code
 * primitives Pi does not ship: `Task` (spawn a single-shot subagent from
 * an agent charter) and `AskUserQuestion` (the Owner gate). This module
 * registers Pi tools with the SAME names and compatible parameter shapes,
 * so the workflow prose ("spawn `dcs-situation-analyst` via Task", "ask
 * the Owner via AskUserQuestion") maps onto the tools the model actually
 * sees under Pi.
 *
 * Task: spawns a separate `pi` process per invocation (isolated context
 * window), reading the charter from `<cwd>/.dcs/agents/<name>.md` (the
 * PROJECT-LOCAL override, searched first so an onboarded project can pin
 * its own seats), then ~/.pi/agent/agents/<name>.md (the transformed DCS
 * charters) with a fallback to ~/.claude/agents/<name>.md for projects
 * onboarded under Claude Code. The charter's `tools` line is
 * already in Pi tool names (pi_transform.py class (e)); its `model:` line
 * is the SEAT (commander/chief/safety-officer/specialist/analyst/weak),
 * resolved to a
 * provider/modelId through the flat seat_models map at spawn time. A
 * `model` override on the Task call is resolved the same way: a seat name
 * goes through the seat map, any other string passes verbatim as a literal
 * provider/model id. Single-shot only -- DCS never resumes an agent.
 *
 * AskUserQuestion: turns each question into a ctx.ui.select() prompt and
 * returns the Owner's answers as text. multiSelect questions are answered
 * through repeated single selects (one option at a time) with a "done"
 * sentinel, which is the closest ctx.ui offers to Claude's checkbox
 * widget; the difference is documented, not hidden.
 *
 * Runtime deps (resolved from pi's bundled core packages, never bundled
 * here): typebox for the schemas, node:child_process for the subagent
 * spawn. The importing extension (dcs/bridge-pi/index.ts) calls
 * registerTaskTools(pi) from its default export.
 */
import { spawn } from "node:child_process";
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
import { join } from "node:path";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { Type } from "typebox";

const TASK_TIMEOUT_MS = 10 * 60 * 1000; // 10 minutes: DCS agents are single-shot but may run tests

interface Charter {
  name: string;
  systemPrompt: string;
  tools: string[];
  model?: string;
}

// Claude Code tool names -> Pi tool names. Charters read from the
// ~/.claude/agents/ fallback still carry the Claude spelling (and the
// Pi-installed charters already carry the lowercase form), so the mapping
// is applied at parse time regardless of source; unknown names
// (mcp__codegraph__*) are dropped the same way pi_transform.py drops them.
const TOOL_NAME_MAP: Record<string, string> = {
  Read: "read",
  Grep: "grep",
  Glob: "find",
  Bash: "bash",
  Edit: "edit",
  Write: "write",
};

function mapTools(raw: string[]): string[] {
  const out: string[] = [];
  for (const t of raw) {
    const mapped = TOOL_NAME_MAP[t] ?? t;
    if (/^[a-z_]+$/.test(mapped)) out.push(mapped);
  }
  return out;
}

function parseCharter(markdown: string, fallbackName: string): Charter {
  const tools: string[] = [];
  let model: string | undefined;
  let systemPrompt = markdown;
  const m = markdown.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
  if (m) {
    const frontmatter = m[1];
    systemPrompt = markdown.slice(m[0].length);
    for (const line of frontmatter.split(/\r?\n/)) {
      const key = line.match(/^([A-Za-z_]+):\s*(.*)$/);
      if (!key) continue;
      const k = key[1];
      const v = key[2].trim();
      if (k === "tools" && v) {
        tools.push(
          ...v.split(",").map((t) => t.trim()).filter(Boolean),
        );
      } else if (k === "model" && v) {
        model = v; // the seat: commander/chief/safety-officer/specialist/analyst/weak
      }
    }
  }
  return { name: fallbackName, systemPrompt: systemPrompt.trim(), tools: mapTools(tools), model };
}

function findCharter(name: string, agentDirs: string[]): { path: string; charter: Charter } | null {
  for (const dir of agentDirs) {
    const p = join(dir, `${name}.md`);
    if (existsSync(p)) {
      try {
        return { path: p, charter: parseCharter(readFileSync(p, "utf8"), name) };
      } catch {
        /* fall through */
      }
    }
  }
  return null;
}

function getPiInvocation(args: string[]): { command: string; args: string[] } {
  const currentScript = process.argv[1];
  if (currentScript && !currentScript.startsWith("/$bunfs/root/") && existsSync(currentScript)) {
    return { command: process.execPath, args: [currentScript, ...args] };
  }
  const execName = (process.execPath.split(/[\\/]/).pop() || "").toLowerCase();
  const isGenericRuntime = /^(node|bun)(\.exe)?$/.test(execName);
  if (!isGenericRuntime) {
    return { command: process.execPath, args };
  }
  return { command: "pi", args };
}

// The child's JSON-mode stream carries, on each assistant `message_end`
// event, the provider-reported usage object (`input`/`output`/`cacheRead`/
// `cacheWrite`/`totalTokens` plus a `cost` object, and `reasoning` ONLY on
// providers that report one -- measured 2026-10-12: 87 of 8,694 assistant
// records lack it) alongside the identity fields the token report needs
// (`provider`, `model`, and `responseModel` when present: a virtual/seat-
// resolved id can be answered by a different physical model). This helper
// extracts the LAST such event's capture over complete JSONL lines; absent
// stays absent -- `reasoning` (and every other field) is never defaulted to
// zero, so an unmeasured quantity can never masquerade as a free one.
// The fenced region below is sliced out and run standalone by
// tests/test_install_targets.py: it must stay free of any module reference.
// dcs:task-usage:begin
interface TaskUsage {
  input?: number;
  output?: number;
  cacheRead?: number;
  cacheWrite?: number;
  totalTokens?: number;
  reasoning?: number; // provider-dependent: omitted, never zero-filled
}

interface TaskUsageCapture {
  usage?: TaskUsage;
  provider?: string;
  model?: string;
  responseModel?: string;
}

function extractTaskUsage(lines: string[]): TaskUsageCapture {
  const out: TaskUsageCapture = {};
  for (const line of lines) {
    if (!line.trim()) continue;
    let evt: unknown;
    try {
      evt = JSON.parse(line);
    } catch {
      continue; // not a complete JSON line yet
    }
    if (!evt || typeof evt !== "object") continue;
    const e = evt as { type?: string; message?: Record<string, unknown> };
    if (e.type !== "message_end" || !e.message) continue;
    const msg = e.message;
    if (msg.role !== "assistant") continue;
    if (typeof msg.provider === "string") out.provider = msg.provider;
    if (typeof msg.model === "string") out.model = msg.model;
    // present only when the answering physical model differs from the
    // requested id; copied when reported, never invented from `model`
    if (typeof msg.responseModel === "string") out.responseModel = msg.responseModel;
    const usage = msg.usage;
    if (usage && typeof usage === "object") {
      const src = usage as Record<string, unknown>;
      const u: TaskUsage = {};
      if (typeof src.input === "number") u.input = src.input;
      if (typeof src.output === "number") u.output = src.output;
      if (typeof src.cacheRead === "number") u.cacheRead = src.cacheRead;
      if (typeof src.cacheWrite === "number") u.cacheWrite = src.cacheWrite;
      if (typeof src.totalTokens === "number") u.totalTokens = src.totalTokens;
      // provider-dependent: copied ONLY when reported, never zero-filled
      if (typeof src.reasoning === "number") u.reasoning = src.reasoning;
      // `cost` is deliberately NOT carried: the report counts tokens, not
      // currency, and a provider's cost object is not a token split.
      out.usage = u;
    }
  }
  return out;
}

// Renders the captured usage as ONE model-facing line using the fence's own
// vocabulary -- the `field=value` tokens (input=/output=/cacheRead=/cacheWrite=/
// totalTokens=, plus reasoning= ONLY when the provider reported one) are the
// pinned contract; the leading label text is free. Absent usage yields the
// empty string (no line), and every field is emitted ONLY when the capture
// carried it -- never zero-filled, so an unmeasured quantity cannot masquerade
// as a free one (the ledger's `usage: "unavailable"` marker is S2's tool, not
// this formatter). Import-free, like the rest of the fenced region.
function formatTaskUsageLine(capture: TaskUsageCapture): string {
  const u = capture.usage;
  if (!u) return "";
  const parts: string[] = [];
  if (typeof u.input === "number") parts.push(`input=${u.input}`);
  if (typeof u.output === "number") parts.push(`output=${u.output}`);
  if (typeof u.cacheRead === "number") parts.push(`cacheRead=${u.cacheRead}`);
  if (typeof u.cacheWrite === "number") parts.push(`cacheWrite=${u.cacheWrite}`);
  if (typeof u.totalTokens === "number") parts.push(`totalTokens=${u.totalTokens}`);
  // provider-dependent: appended ONLY when reported, never zero-filled
  if (typeof u.reasoning === "number") parts.push(`reasoning=${u.reasoning}`);
  if (parts.length === 0) return "";
  return `usage ${parts.join(" ")}`;
}
// dcs:task-usage:end

interface TaskRun {
  exitCode: number;
  text: string;
  stderr: string;
  usage?: TaskUsage;
  provider?: string;
  model?: string;
  responseModel?: string;
}

// Single content-rendering call site invoked once per Task `execute` branch
// (failure and success): appends the formatter's model-facing usage line to
// the existing branch text when a usage capture exists, else returns the text
// unchanged. The two `details: { exitCode: ... }` literals stay byte-identical
// and this helper adds no second extractTaskUsage call site -- it only reads
// the already-captured run.usage.
function withTaskUsageLine(text: string, run: TaskRun): string {
  const line = formatTaskUsageLine({ usage: run.usage, provider: run.provider, model: run.model, responseModel: run.responseModel });
  if (!line) return text;
  return `${text}\n${line}`;
}

function runTaskCharter(
  charter: Charter,
  prompt: string,
  cwd: string,
  model: string | undefined,
  thinkingLevel: string | undefined,
  signal: AbortSignal | undefined,
): Promise<TaskRun> {
  return new Promise((resolveTask) => {
    const args: string[] = ["--mode", "json", "-p", "--no-session"];
    if (model) args.push("--model", model);
    if (thinkingLevel) args.push("--thinking", thinkingLevel);
    if (charter.tools.length > 0) args.push("--tools", charter.tools.join(","));

    let promptDir: string | null = null;
    let promptPath: string | null = null;
    try {
      if (charter.systemPrompt) {
        promptDir = mkdtempSync(join(tmpdir(), "dcs-task-"));
        promptPath = join(promptDir, "system-prompt.md");
        writeFileSync(promptPath, charter.systemPrompt, "utf8");
        args.push("--append-system-prompt", promptPath);
      }
    } catch {
      // a missing system-prompt temp file degrades to no charter context;
      // the task text still reaches the subagent verbatim
    }

    args.push(`Task: ${prompt}`);

    const invocation = getPiInvocation(args);
    let child;
    try {
      child = spawn(invocation.command, invocation.args, {
        cwd,
        shell: false,
        stdio: ["ignore", "pipe", "pipe"],
      });
    } catch (e) {
      resolveTask({ exitCode: 1, text: "", stderr: `spawn failed: ${(e as Error).message}` });
      if (promptDir) try { rmSync(promptDir, { recursive: true, force: true }); } catch { /* ignore */ }
      return;
    }

    let stdout = "";
    let stderr = "";
    let settled = false;
    let text = "";
    // usage + identity captured from the child's assistant message_end events
    // (see extractTaskUsage); absent when the child emitted no parseable
    // message_end, never zero-filled.
    let usageCap: TaskUsage | undefined;
    let providerCap: string | undefined;
    let modelCap: string | undefined;
    let responseModelCap: string | undefined;

    const finish = (exitCode: number) => {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      if (promptDir) try { rmSync(promptDir, { recursive: true, force: true }); } catch { /* ignore */ }
      resolveTask({ exitCode, text, stderr, usage: usageCap, provider: providerCap, model: modelCap, responseModel: responseModelCap });
    };

    const timer = setTimeout(() => {
      try { child.kill(); } catch { /* already gone */ }
      stderr += `\n[dcs-task] timed out after ${TASK_TIMEOUT_MS}ms`;
      finish(1);
    }, TASK_TIMEOUT_MS);

    child.stdout.on("data", (chunk: Buffer) => {
      stdout += chunk.toString("utf8");
      // JSON-mode pi emits one JSON object per line; the last assistant
      // text is the subagent's deliverable.
      const lines = stdout.split("\n");
      for (const line of lines.slice(0, -1)) {
        if (!line.trim()) continue;
        try {
          const evt = JSON.parse(line);
          if (evt && evt.type === "message_end" && evt.message?.role === "assistant") {
            const parts = (evt.message.content || []) as Array<{ type?: string; text?: string }>;
            const t = parts
              .filter((p) => p && p.type === "text" && typeof p.text === "string")
              .map((p) => p.text)
              .join("\n");
            if (t) text = t;
          }
        } catch {
          /* not a complete JSON line yet */
        }
      }
      // usage + identity capture for the token report: the same complete-line
      // window the text scan above consumed, extracted through the pure
      // fence helper; the last assistant message_end wins, which is pi's
      // "latest cumulative provider-reported usage".
      const cap = extractTaskUsage(lines.slice(0, -1));
      if (cap.usage) usageCap = cap.usage;
      if (cap.provider !== undefined) providerCap = cap.provider;
      if (cap.model !== undefined) modelCap = cap.model;
      if (cap.responseModel !== undefined) responseModelCap = cap.responseModel;
    });
    child.stderr.on("data", (chunk: Buffer) => {
      stderr += chunk.toString("utf8");
    });
    child.on("error", () => finish(1));
    child.on("close", (code: number | null) => finish(code ?? 0));

    if (signal) {
      const killProc = () => {
        try { child.kill(); } catch { /* already gone */ }
      };
      if (signal.aborted) killProc();
      else signal.addEventListener("abort", killProc, { once: true });
    }
  });
}

function defaultAgentDirs(cwd: string): string[] {
  const home = process.env.HOME || process.env.USERPROFILE || "";
  const dirs: string[] = [];
  // Project-local charters win over the installed home charters: a project
  // that pins its own seats (the weak-model conformance eval is the first
  // such consumer) must not be silently overridden by ~/.pi/agent/agents or
  // ~/.claude/agents. `findCharter` returns the first hit, so order is the
  // whole precedence rule.
  // An empty cwd yields only the two home dirs -- no relative `.dcs/agents`
  // entry resolved against process.cwd() by findCharter.
  if (cwd) dirs.push(join(cwd, ".dcs", "agents"));
  if (home) {
    dirs.push(join(home, ".pi", "agent", "agents"));
    dirs.push(join(home, ".claude", "agents"));
  }
  return dirs;
}

function seatMapPath(): string {
  return join(homedir(), ".pi", "agent", "dcs-seats.json");
}

function readSeatMap(projectRoot: string): Record<string, string> {
  const map: Record<string, string> = {};
  try {
    const raw = JSON.parse(readFileSync(seatMapPath(), "utf8"));
    if (raw && typeof raw === "object") {
      for (const [k, v] of Object.entries(raw)) {
        if (typeof v === "string") map[k] = v;
      }
    }
  } catch {
    /* absent or malformed -- default below */
  }
  try {
    const cfg = JSON.parse(readFileSync(join(projectRoot, ".dcs", "config.json"), "utf8"));
    const over = (cfg && typeof cfg === "object" ? cfg as { seat_models?: unknown } : {}).seat_models;
    if (over && typeof over === "object") {
      for (const [k, v] of Object.entries(over)) {
        if (typeof v === "string") map[k] = v;
      }
    }
  } catch {
    /* absent -- keep global/default */
  }
  return map;
}

// The flat cross-provider seat->model map, read at spawn. `dcs-seats.json`
// is the Owner-editable source of truth; a per-project `.dcs/config.json`
// `seat_models` key overrides it. The DEFAULT_SEAT_MAP is the DeepSeek
// fallback when neither config names a seat; any other provider resolves
// every seat to the session's active model.
// The fenced region below is sliced out and run standalone by
// tests/test_install_targets.py: it must stay free of any module reference.
// dcs:seat-resolution:begin
const DEFAULT_SEAT_MAP: Record<string, string> = {
  commander: "deepseek/deepseek-v4-pro",
  chief: "deepseek/deepseek-v4-pro",
  "safety-officer": "deepseek/deepseek-v4-pro",
  specialist: "deepseek/deepseek-v4-flash",
  analyst: "deepseek/deepseek-v4-flash",
  weak: "deepseek/deepseek-v4-flash",
};

const SEAT_TIERS = new Set(["commander", "chief", "safety-officer", "specialist", "analyst", "weak"]);

function resolveSeatModel(
  tier: string | undefined,
  activeProvider: string,
  activeModelId: string,
  seatMap: Record<string, string>,
): string {
  if (tier && seatMap[tier]) return seatMap[tier];
  if (activeProvider === "deepseek" && tier && DEFAULT_SEAT_MAP[tier]) {
    return DEFAULT_SEAT_MAP[tier];
  }
  return `${activeProvider}/${activeModelId}`;
}

// A `model` override matches by its normalised (trimmed, lower-cased)
// form: a seat name in any case or with surrounding whitespace resolves
// through the seat map like a charter seat; an empty or whitespace-only
// override means "omitted" and resolves from the charter seat; anything
// else is a literal provider/model id and passes through byte-identical,
// never the normalised form.
export function resolveTaskModel(
  override: unknown,
  charterTier: string | undefined,
  activeProvider: string,
  activeModelId: string,
  seatMap: Record<string, string>,
): string {
  const key = typeof override === "string" ? override.trim().toLowerCase() : undefined;
  if (typeof override === "string" && key !== "" && !SEAT_TIERS.has(key as string)) return override;
  return resolveSeatModel(
    key === "" || key === undefined ? charterTier : key,
    activeProvider,
    activeModelId,
    seatMap,
  );
}

// Pi's `--model <provider>/<id>:<level>` suffix natively sets the child's
// thinking level, but runTaskCharter pushes an explicit `--thinking`, and
// that wins over the suffix. So the Task call site derives the effective
// level from the RESOLVED model -- a seat-map value or a literal override,
// either of which may carry the native suffix: a suffix that is one of
// Pi's seven valid levels wins, and everything else (a bare value, or a
// non-level suffix such as `openrouter/x:exacto`) keeps the parent
// session's level exactly as it did before this resolver existed.
// Reconcile this set against Pi's own VALID_THINKING_LEVELS in
// dist/cli/args.js: a level Pi adds later is not recognised here, and the
// child silently falls back to the parent level. (Safety advisory 1,
// incident pi-seat-effort-selection, 2026-10-03.)
const SEAT_EFFORT_LEVELS = new Set([
  "off", "minimal", "low", "medium", "high", "xhigh", "max",
]);

export function resolveSeatEffort(
  resolvedModel: string,
  parentLevel: string | undefined,
): string | undefined {
  const i = resolvedModel.lastIndexOf(":");
  const suffix = i >= 0 ? resolvedModel.slice(i + 1) : "";
  if (SEAT_EFFORT_LEVELS.has(suffix)) return suffix;
  return parentLevel;
}

// The seat the Task call site asked for, resolved through the same normalisation
// resolveTaskModel applies: a seat name in any case/whitespace normalises to its
// tier key; a literal provider/model id passes through byte-identical; an omitted
// or empty override falls back to the charter seat; no seat at all yields "".
export function resolveRequestedSeat(override: unknown, charterTier: string | undefined): string {
  const key = typeof override === "string" ? override.trim().toLowerCase() : undefined;
  if (typeof override === "string" && key !== "" && !SEAT_TIERS.has(key as string)) return override;
  const effectiveTier = key === "" || key === undefined ? charterTier : key;
  return effectiveTier ?? "";
}

// null when the host reports the resolved id available -- either verbatim, or via
// a recognised `:level` suffix stripped iff the suffix is one of SEAT_EFFORT_LEVELS
// (a non-level suffix such as `:exacto` must match verbatim). Otherwise the frozen
// loud-fail message naming the seat, the resolved id and every available id.
export function unavailableSeatError(seat: string, resolvedModel: string, available: string[]): string | null {
  if (available.includes(resolvedModel)) return null;
  const i = resolvedModel.lastIndexOf(":");
  const suffix = i >= 0 ? resolvedModel.slice(i + 1) : "";
  if (SEAT_EFFORT_LEVELS.has(suffix)) {
    const base = resolvedModel.slice(0, i);
    if (available.includes(base)) return null;
  }
  return `Seat "${seat}" resolved to "${resolvedModel}", which the host does not report as available. Host reports available: ${available.join(", ")}.`;
}
// dcs:seat-resolution:end

// dcs:models-picker:begin
// Pi exposes three catalogue views. The two "availability" ones are
// auth-filtered, and that gate drops every provider whose credential never
// reaches `provider.auth.apiKey` — measured on this machine 2026-10-03:
// `pi auth check --provider localllm-ninfer` prints `not_ready` while
// `--provider deepseek` prints `ready`, so the live `getAvailableOfType` AND
// the `getAvailable()` snapshot BOTH omit the local provider's `qwen3.8-27b`.
// Only the unfiltered `getAll()` enumerates it, and `getProviderAuthStatus()`
// is the one accessor that separates "the operator configured this provider"
// (an extension registration with a flat `apiKey` reports
// `{configured:true, source:"fallback"}`) from "a built-in nobody set up"
// (`{configured:false}`). So: union the two availability views and add every
// `getAll()` model whose provider is configured. A seat map accepts any id
// and the spawn path now consults that same union before spawning and fails
// loudly when the resolved id is absent from it — a real spawn on the
// `specialist` seat, whose map points at the local model, still succeeds — so the
// picker must offer what Pi has configured rather than only what passes an
// auth gate. Ordering matters as much as membership: see the hidden-first
// comment inside the function.
export async function readModelChoices(
  registry: {
    getAvailableOfType(type: string): Promise<unknown[]>;
    getAvailable(): Promise<unknown[]>;
    getAll(): Promise<unknown[]>;
    getProviderAuthStatus(provider: string): { configured?: boolean } | undefined;
  },
): Promise<string[]> {
  const [live, snapshot, all] = await Promise.all([
    registry.getAvailableOfType("chat"),
    registry.getAvailable(),
    registry.getAll(),
  ]);
  const idOf = (m: { provider?: string; id?: string }): string => `${m.provider}/${m.id}`;
  const hasSlash = (s: string): boolean => s.includes("/");
  // What either availability view offers: the models that pass the auth gate.
  const offered = new Set<string>();
  for (const m of [...live, ...snapshot] as Array<{ provider?: string; id?: string }>) {
    const choice = idOf(m);
    if (hasSlash(choice)) offered.add(choice);
  }
  // Configured providers only; a built-in nobody set up reports configured:false.
  const seen = new Set<string>(offered);
  const hidden: string[] = [];
  for (const m of all as Array<{ provider?: string; id?: string }>) {
    if (!m.provider || registry.getProviderAuthStatus(m.provider)?.configured !== true) continue;
    const choice = idOf(m);
    if (!hasSlash(choice) || seen.has(choice)) continue;
    // Configured, but neither availability view lists it: this is exactly the
    // extension-registered local-server case. `ctx.ui.select` is a short-list
    // selector -- it renders every option with no viewport, no search and no
    // page keys -- so an entry buried at the end of a 400-row list is
    // unreachable. Surface these FIRST; they are few, and they are the ones a
    // model picker is most likely to be asked for.
    seen.add(choice);
    hidden.push(choice);
  }
  return [...hidden, ...[...offered].sort()];
}
// dcs:models-picker:end

// `ctx.ui.select` is Pi's own short-list selector: it renders EVERY option with
// no viewport, no search and no page keys, so a full catalogue is unnavigable
// and anything below the screen is unreachable. This filter plus the search
// loop in the `/dcs-models` handler is the extension-side answer: ask for a
// substring, then hand `select` only the matches. Deliberately OUTSIDE the
// fence above, whose sliced driver must stay untouched.
export function filterModelChoices(choices: string[], needle: string): string[] {
  const q = needle.trim().toLowerCase();
  if (!q) return choices;
  return choices.filter((c) => c.toLowerCase().includes(q));
}

interface QuestionSpec {
  question?: string;
  header?: string;
  options?: Array<{ label?: string; description?: string }>;
  multiSelect?: boolean;
}

function optionLabel(o: { label?: string; description?: string } | undefined, i: number): string {
  if (!o) return `Option ${i + 1}`;
  const label = o.label && o.label.trim() ? o.label.trim() : `Option ${i + 1}`;
  return o.description && o.description.trim()
    ? `${label} — ${o.description.trim()}`
    : label;
}

export function registerTaskTools(pi: ExtensionAPI): void {
  pi.registerTool({
    name: "Task",
    label: "Task",
    description: [
      "Launch a single-shot subagent from a DCS charter (agents/*.md).",
      "Provide subagent_type (the charter name), a prompt, and a short description.",
      "The subagent runs in an isolated pi process and returns its final text.",
    ].join(" "),
    parameters: Type.Object({
      description: Type.String({ description: "Short 3-5 word description of the task" }),
      prompt: Type.String({ description: "The full task text for the subagent" }),
      subagent_type: Type.String({ description: "Charter name, e.g. dcs-situation-analyst" }),
      model: Type.Optional(Type.String({ description: "Optional model override: either a seat (commander/chief/safety-officer/specialist/analyst/weak), resolved through the seat map, or a literal provider/model id, passed through unchanged" })),
    }),
    async execute(_toolCallId, params, signal, _onUpdate, ctx) {
      const found = findCharter(String(params.subagent_type), defaultAgentDirs(ctx.cwd));
      if (!found) {
        return {
          content: [{
            type: "text",
            text: `Unknown subagent_type: "${params.subagent_type}". No charter found under .dcs/agents/, ~/.pi/agent/agents/ or ~/.claude/agents/.`,
          }],
          details: {},
        };
      }
      const seatMap = readSeatMap(ctx.cwd);
      const activeProvider = ctx.model?.provider ?? "unknown";
      const activeModelId = ctx.model?.id ?? "";
      const resolvedModel = resolveTaskModel(params.model, found.charter.model, activeProvider, activeModelId, seatMap);
      const requestedSeat = resolveRequestedSeat(params.model, found.charter.model);
      if (requestedSeat) {
        const availableModels = await readModelChoices(ctx.modelRegistry);
        const availabilityError = unavailableSeatError(requestedSeat, resolvedModel, availableModels);
        if (availabilityError) {
          return { content: [{ type: "text", text: availabilityError }], details: {}, isError: true };
        }
      }
      const effectiveThinking = resolveSeatEffort(resolvedModel, ctx.thinkingLevel);
      const run = await runTaskCharter(
        found.charter,
        String(params.prompt),
        ctx.cwd,
        resolvedModel,
        effectiveThinking,
        signal,
      );
      if (run.exitCode !== 0) {
        return {
          content: [{
            type: "text",
            text: withTaskUsageLine(`Subagent "${params.subagent_type}" failed (exit ${run.exitCode}).${run.stderr ? `\n${run.stderr}` : ""}${run.text ? `\n${run.text}` : ""}`, run),
          }],
          details: { exitCode: run.exitCode, usage: run.usage, provider: run.provider, model: run.model, responseModel: run.responseModel },
          isError: true,
        };
      }
      return {
        content: [{ type: "text", text: withTaskUsageLine(run.text || "(no output)", run) }],
        details: { exitCode: 0, usage: run.usage, provider: run.provider, model: run.model, responseModel: run.responseModel },
      };
    },
  });

  pi.registerTool({
    name: "AskUserQuestion",
    label: "AskUserQuestion",
    description: [
      "Ask the Owner one or more questions and return their answers.",
      "Each question needs options; the Owner picks one (or several for multiSelect).",
    ].join(" "),
    parameters: Type.Object({
      questions: Type.Array(Type.Object({
        question: Type.Optional(Type.String()),
        header: Type.Optional(Type.String()),
        options: Type.Optional(Type.Array(Type.Object({
          label: Type.Optional(Type.String()),
          description: Type.Optional(Type.String()),
        }))),
        multiSelect: Type.Optional(Type.Boolean()),
      })),
    }),
    async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
      const questions = (params.questions || []) as QuestionSpec[];
      const answers: string[] = [];
      for (let i = 0; i < questions.length; i++) {
        const q = questions[i];
        if (!ctx.hasUI) {
          // Non-interactive: no Owner to answer. Return the first option
          // with a marker so the workflow can detect it was not a real
          // human choice -- never fabricate a silent answer.
          answers.push(`[no UI] ${q.question || q.header || `question ${i + 1}`}`);
          continue;
        }
        const title = q.header || q.question || `Question ${i + 1}`;
        const options = (q.options || []).map((o, j) => optionLabel(o, j));
        if (options.length === 0) {
          const text = await ctx.ui.input(title, "");
          answers.push(`${title}: ${text}`);
          continue;
        }
        if (q.multiSelect) {
          const picked: string[] = [];
          for (;;) {
            const choice = await ctx.ui.select(title, ["[done]", ...options]);
            if (!choice || choice === "[done]") break;
            picked.push(choice);
          }
          answers.push(`${title}: ${picked.join("; ") || "(none selected)"}`);
        } else {
          const choice = await ctx.ui.select(title, options);
          answers.push(`${title}: ${choice || ""}`);
        }
      }
      return {
        content: [{ type: "text", text: answers.join("\n") }],
        details: {},
      };
    },
  });

  pi.registerCommand("dcs-models", {
    description: "View and reassign the DCS seat->model map (model + reasoning effort)",
    handler: async (_args, ctx) => {
      if (!ctx.hasUI) {
        ctx.ui.notify("dcs-models needs an interactive session", "warning");
        return;
      }
      const seats = ["commander", "chief", "safety-officer", "specialist", "analyst", "weak"];
      const seatLabels: Record<string, string> = {
        commander: "Commander (IC)",
        chief: "Chiefs",
        "safety-officer": "Safety Officer",
        specialist: "Specialist",
        analyst: "Analyst",
        weak: "Weak seat (eval)",
      };
      // Pi's seven valid reasoning-effort levels, plus `inherit` -- "no
      // suffix", i.e. the child inherits the parent session's thinking
      // level, exactly as a bare seat value does.
      const effortChoices = ["off", "minimal", "low", "medium", "high", "xhigh", "max", "inherit"];
      const seatMap = readSeatMap(ctx.cwd);
      const activeProvider = ctx.model?.provider ?? "unknown";
      const activeModelId = ctx.model?.id ?? "";
      const choices = await readModelChoices(ctx.modelRegistry);

      // Each seat's current effort: its value's suffix when that suffix is
      // one of Pi's seven levels, `inherit` otherwise (a bare value or an
      // unrecognised suffix) -- the same reading resolveSeatEffort applies
      // at spawn time, so the display never disagrees with the spawn.
      const current = seats
        .map((s) => {
          const value = resolveSeatModel(s, activeProvider, activeModelId, seatMap);
          return `${s} (${seatLabels[s]}): ${value} [effort: ${resolveSeatEffort(value, "inherit") ?? "inherit"}]`;
        })
        .join("\n");
      const seat = await ctx.ui.select(`Seat->model map\n${current}\n\nPick a seat to reassign, or [done]:`, ["[done]", ...seats]);
      if (!seat || seat === "[done]") return;

      // Pi's `ctx.ui.select` renders every option with no viewport, no search
      // and no page keys, so the full catalogue is unnavigable and models below
      // the screen cannot be reached at all. Ask for a substring and offer only
      // the matches. The cap keeps the list inside one screenful, the seat's
      // current value is always offered first so it can be kept as-is, and
      // [back] is offered first so narrowing again is one keystroke.
      const MODEL_LIST_CAP = 25;
      const currentValue = resolveSeatModel(seat, activeProvider, activeModelId, seatMap);
      let model: string | undefined;
      for (;;) {
        const needle = await ctx.ui.input(
          `Search models for ${seat} — type part of a provider/model name `
          + `(${choices.length} available; try "localllm", "anthropic", "deepseek", "qwen"). `
          + `Submit empty to cancel:`,
          "",
        );
        if (!needle) return;
        const matches = filterModelChoices(choices, needle);
        if (matches.length === 0) {
          ctx.ui.notify(`No model matches "${needle}" — try a shorter substring.`, "warning");
          continue;
        }
        if (matches.length > MODEL_LIST_CAP) {
          ctx.ui.notify(
            `"${needle}" matches ${matches.length} models (limit ${MODEL_LIST_CAP}) — narrow it further.`,
            "warning",
          );
          continue;
        }
        const picked = await ctx.ui.select(
          `Model for ${seat} (${seatLabels[seat]}) — ${matches.length} match(es) for "${needle}":`,
          ["[back]", currentValue, ...matches.filter((m) => m !== currentValue)],
        );
        if (!picked) return;
        if (picked === "[back]") continue;
        model = picked;
        break;
      }
      if (!model) return;

      const effort = await ctx.ui.select(
        `Reasoning effort for ${seat} on ${model} -- inherit = the child inherits this session's thinking level:`,
        effortChoices,
      );
      if (!effort) return;
      // `inherit` writes a bare value (no suffix); any level recomposes the
      // model with the native `:<level>` suffix, which the spawn path's
      // resolveSeatEffort reads back at Task time.
      seatMap[seat] = effort === "inherit" ? model : `${model}:${effort}`;
      try {
        writeFileSync(seatMapPath(), JSON.stringify(seatMap, null, 2) + "\n", "utf8");
        ctx.ui.notify(`dcs-seats.json updated: ${seat} -> ${seatMap[seat]}`, "info");
      } catch (e) {
        ctx.ui.notify(`Failed to write dcs-seats.json: ${(e as Error).message}`, "error");
      }
    },
  });
}
