/**
 * DCS bridge extension for Pi — transport only, no policy.
 *
 * Pi is the third harness this package installs under. Its extension
 * system exposes lifecycle events (tool_call can block, tool_result can
 * modify, before_agent_start can inject a message, agent_settled fires
 * when the agent has no follow-up left) that map onto the four DCS
 * Python hooks that have a Pi seam:
 *
 *   tool_call            -> dcs_gate.py            (may deny)
 *   before_agent_start   -> dcs_intake.py          (advisory note, never blocks)
 *   tool_result          -> register_view_regen.py (advisory context, never blocks)
 *   agent_settled        -> dcs_stop.py            (best-effort; see below)
 *
 * NO POLICY IN TS: every allow/deny/fold decision is read from the
 * spawned hook's stdout. The bridge never inspects tool arguments to
 * decide an outcome — it routes, spawns, translates shapes, and fails
 * open. The one routing judgment it makes is WHICH calls are worth a
 * spawn: write/edit calls carrying a file target for the gate and regen,
 * the first agent run of a session for intake, and a settled agent for
 * stop. Everything else short-circuits without a spawn, exactly like the
 * gate's zero-overhead silence outside DCS projects.
 *
 * Fail-open WITH A LOUD stderr line, separately per adapter, on each of:
 * spawn failure, nonzero child exit, unparseable non-empty child stdout,
 * child timeout. "unparseable" is reserved for non-empty non-JSON
 * stdout; an exit-0 child whose stdout is empty or whitespace-only is a
 * silent allow — a null parsed body, no log line — because a hook that
 * chose to say nothing has allowed, not degraded. A missing hook script
 * in the target tree is NOT a failure — quiet pass-through, because an
 * unhooked tree is normal operation.
 *
 * Node stdlib ONLY: node:child_process, node:fs, node:os, node:path.
 * The single type import below is erased at runtime, so this extension
 * has zero runtime dependencies and needs no node_modules beside it.
 *
 * The SubagentStop hook (dcs/hooks/return_check.py) has NO Pi seam: Pi
 * extensions cannot observe a subagent's stop/return. It is documented
 * as not portable in dcs/bridge-pi/README.md, never fabricated.
 */
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { spawn } from "node:child_process";
import { existsSync, statSync } from "node:fs";
import { platform } from "node:os";
import { dirname, isAbsolute, join, resolve } from "node:path";
import { registerTaskTools } from "./task-tools.ts";

const HOOK_TIMEOUT_MS = 30000;

/** Pi model-facing tool names -> Claude-shaped names the Python hooks
 * branch on. Pi registers write/edit/read with argument key `path`; the
 * gate and regen hooks only ever care about Write/Edit. notebook_edit
 * does not exist in Pi today; the mapping is forward-compat only.
 * Unmapped names pass through unchanged. */
const TOOL_NAME_MAP: Record<string, string> = {
  write: "Write",
  edit: "Edit",
  notebook_edit: "NotebookEdit",
};

function mapToolName(name: string): string {
  return Object.prototype.hasOwnProperty.call(TOOL_NAME_MAP, name)
    ? TOOL_NAME_MAP[name]
    : name;
}

function pythonExecutable(): string {
  return process.env.DCS_PYTHON || "python";
}

function boolEnv(name: string, fallback: boolean): boolean {
  const v = process.env[name];
  if (v === undefined) return fallback;
  const s = v.trim().toLowerCase();
  if (s === "" || s === "1" || s === "true" || s === "yes" || s === "on") {
    return true;
  }
  if (s === "0" || s === "false" || s === "no" || s === "off") {
    return false;
  }
  return fallback;
}

function logLoud(adapterId: string, message: string): void {
  console.error(`[dcs-bridge-pi] ${adapterId}: ${message}`);
}

/** win32 normcase semantics (lowercased, backslashes folded), matching
 * dcs/hooks/register_view_regen.py's own path comparison. */
function normcase(p: string): string {
  const lowered = String(p).toLowerCase();
  return platform() === "win32" ? lowered.replace(/\//g, "\\") : lowered;
}

/**
 * Project resolution mirroring dcs_gate.py's find_project_root(): walk up
 * from the TARGET's own absolute directory looking for .dcs/, falling
 * back to a walk from cwd. Returns null when no DCS-onboarded root
 * exists. CLAUDE_PROJECT_DIR is intentionally not consulted here — under
 * Pi there is no such variable, and a real target path beats any
 * environment guess.
 */
function resolveProjectRoot(
  targetPath: string | undefined,
  cwd: string,
): string | null {
  let start: string;
  if (targetPath && isAbsolute(targetPath)) {
    start = dirname(resolve(targetPath));
  } else {
    start = resolve(cwd);
  }
  let cur = start;
  for (;;) {
    if (existsSync(join(cur, ".dcs"))) return cur;
    const parent = dirname(cur);
    if (normcase(parent) === normcase(cur)) return null;
    cur = parent;
  }
}

/** Shared-location preference (same as the DSH bridge, decision D3):
 * <project>/.dcs/hooks/<script> first, legacy <project>/.claude/hooks/
 * <script> second. Neither present -> null: not a hooked DCS tree. */
function resolveHookScript(root: string | null, script: string): string | null {
  if (!root) return null;
  for (const rel of [
    join(".dcs", "hooks", script),
    join(".claude", "hooks", script),
  ]) {
    const candidate = join(root, rel);
    try {
      if (statSync(candidate).isFile()) return candidate;
    } catch {
      /* fall through to the next candidate */
    }
  }
  return null;
}

/** Pi's write/edit tools carry the target under `input.path`; the Python
 * hooks read `tool_input.file_path`. This is the one shape translation
 * the bridge performs on the way IN. */
function targetOf(input: unknown): string | null {
  if (input && typeof input === "object" && "path" in input) {
    const p = (input as { path?: unknown }).path;
    if (typeof p === "string" && p) return p;
  }
  return null;
}

type HookOutcome =
  | "ok"
  | "no-hook"
  | "spawn-failed"
  | "nonzero-exit"
  | "unparseable"
  | "timeout";

interface HookRun {
  outcome: HookOutcome;
  parsed?: unknown;
  stderr?: string;
}

/**
 * Spawn one hook and translate its outcome. NEVER throws: every failure
 * mode resolves to a loud, adapter-tagged log line and outcome != "ok".
 * Returns {outcome, parsed, stderr} where parsed is the hook's JSON
 * object when outcome === "ok".
 */
function runHook(
  adapterId: string,
  scriptPath: string | null,
  payloadObj: Record<string, unknown>,
  spawnCwd: string,
  timeoutMs: number = HOOK_TIMEOUT_MS,
): Promise<HookRun> {
  return new Promise((resolveHook) => {
    if (!scriptPath) {
      resolveHook({ outcome: "no-hook" });
      return;
    }
    let child;
    try {
      child = spawn(pythonExecutable(), [scriptPath], {
        cwd: spawnCwd || undefined,
        windowsHide: true,
      });
    } catch (e) {
      logLoud(
        adapterId,
        `spawn failed for ${scriptPath}: ${(e as Error).message} -- failing OPEN`,
      );
      resolveHook({ outcome: "spawn-failed" });
      return;
    }
    let settled = false;
    let stdout = "";
    let stderr = "";
    const finish = (outcome: HookOutcome, parsed?: unknown) => {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      resolveHook({ outcome, parsed, stderr });
    };
    const timer = setTimeout(() => {
      try {
        child.kill();
      } catch {
        /* already gone */
      }
      logLoud(adapterId, `child timed out after ${timeoutMs}ms -- failing OPEN`);
      finish("timeout");
    }, timeoutMs);
    child.on("error", (e: Error) => {
      logLoud(
        adapterId,
        `spawn failed for ${scriptPath}: ${e.message} -- failing OPEN`,
      );
      finish("spawn-failed");
    });
    child.stdout.on("data", (chunk: Buffer) => {
      stdout += chunk.toString("utf8");
    });
    child.stderr.on("data", (chunk: Buffer) => {
      stderr += chunk.toString("utf8");
    });
    child.on("close", (code: number | null) => {
      if (code !== 0) {
        logLoud(
          adapterId,
          `child exited nonzero (code ${code})` +
            (stderr.trim() ? ": " + stderr.trim().slice(0, 300) : "") +
            " -- failing OPEN",
        );
        finish("nonzero-exit");
        return;
      }
      const trimmed = stdout.trim();
      if (!trimmed) {
        finish("ok", null);
        return;
      }
      try {
        finish("ok", JSON.parse(trimmed));
      } catch {
        logLoud(
          adapterId,
          `unparseable child stdout (${String(stdout).trim().slice(0, 120)}) -- failing OPEN`,
        );
        finish("unparseable");
      }
    });
    try {
      child.stdin.write(JSON.stringify(payloadObj));
      child.stdin.end();
    } catch {
      /* close handler will classify; EPIPE surfaces as nonzero exit */
    }
  });
}

interface DecisionContext {
  permissionDecision?: string;
  permissionDecisionReason?: string;
  additionalContext?: string;
  decision?: string;
  reason?: string;
}

function extractDecisionContext(parsed: unknown): DecisionContext | null {
  if (!parsed || typeof parsed !== "object") return null;
  const out = (parsed as { hookSpecificOutput?: unknown }).hookSpecificOutput;
  if (!out || typeof out !== "object") return null;
  return out as DecisionContext;
}

export default function (pi: ExtensionAPI) {
  // The DCS ceremony tools (Task + AskUserQuestion) that the workflows
  // and skill shims are written against. Registered from the same entry
  // point as the hook transport; see dcs/bridge-pi/task-tools.ts.
  registerTaskTools(pi);

  const gateEnabled = boolEnv("DCS_PI_GATE", true);
  const intakeEnabled = boolEnv("DCS_PI_INTAKE", true);
  const regenEnabled = boolEnv("DCS_PI_REGEN", true);
  const stopEnabled = boolEnv("DCS_PI_STOP", true);

  /* ---------------------------------------------------------------- */
  /* Adapter 1: tool_call -> dcs_gate.py (PreToolUse equivalent)       */
  /* ---------------------------------------------------------------- */
  if (gateEnabled) {
    pi.on("tool_call", async (event, ctx) => {
      const adapterId = "gate";
      const toolName = mapToolName(event.toolName);
      if (toolName !== "Write" && toolName !== "Edit") return undefined;

      const target = targetOf(event.input);
      if (!target) return undefined;

      const root = resolveProjectRoot(target, ctx.cwd);
      const script = resolveHookScript(root, "dcs_gate.py");
      const payload = {
        tool_name: toolName,
        tool_input: { file_path: target },
        cwd: root || ctx.cwd,
        session_id: ctx.sessionManager?.getSessionId?.() ?? "",
      };
      const run = await runHook(
        adapterId,
        script,
        payload,
        root || ctx.cwd,
      );
      if (run.outcome === "ok") {
        const out = extractDecisionContext(run.parsed);
        if (out && out.permissionDecision === "deny") {
          return {
            block: true,
            reason: String(out.permissionDecisionReason || ""),
          };
        }
      }
      return undefined;
    });
  }

  /* ---------------------------------------------------------------- */
  /* Adapter 2: before_agent_start -> dcs_intake.py (advisory)         */
  /*                                                                    */
  /* Fires once per (process, session) via an in-memory Set; the hook   */
  /* ALSO keeps its own temp-file marker, so the once-per-session       */
  /* guarantee survives a reload. The note is advisory — never blocks.  */
  /* ---------------------------------------------------------------- */
  if (intakeEnabled) {
    const nudgedSessions = new Set<string>();
    pi.on("before_agent_start", async (event, ctx) => {
      const adapterId = "intake";
      const sessionId = ctx.sessionManager?.getSessionId?.() ?? "unknown-session";
      if (nudgedSessions.has(sessionId)) return undefined;

      const root = resolveProjectRoot(undefined, ctx.cwd);
      if (!root) return undefined; // not DCS-onboarded — nothing to say

      const script = resolveHookScript(root, "dcs_intake.py");
      const run = await runHook(
        adapterId,
        script,
        {
          session_id: sessionId,
          prompt: event.prompt ?? "",
          cwd: ctx.cwd,
        },
        root,
      );
      // Mark checked regardless of output so we do not respawn Python on
      // every turn of a long session (the hook is advisory, not enforced).
      nudgedSessions.add(sessionId);

      if (run.outcome === "ok") {
        const out = extractDecisionContext(run.parsed);
        const context = out?.additionalContext;
        if (context) {
          return {
            message: {
              customType: "dcs-intake",
              content: context,
              display: true,
            },
          };
        }
      }
      return undefined;
    });
  }

  /* ---------------------------------------------------------------- */
  /* Adapter 3: tool_result -> register_view_regen.py (advisory)       */
  /* ---------------------------------------------------------------- */
  if (regenEnabled) {
    pi.on("tool_result", async (event, ctx) => {
      const adapterId = "regen";
      const toolName = mapToolName(event.toolName);
      if (toolName !== "Write" && toolName !== "Edit") return undefined;

      const target = targetOf(event.input);
      if (!target) return undefined;

      const root = resolveProjectRoot(target, ctx.cwd);
      const script = resolveHookScript(root, "register_view_regen.py");
      const run = await runHook(
        adapterId,
        script,
        {
          tool_name: toolName,
          tool_input: { file_path: target },
          cwd: root || ctx.cwd,
          session_id: ctx.sessionManager?.getSessionId?.() ?? "",
        },
        root || ctx.cwd,
      );
      if (run.outcome === "ok") {
        const out = extractDecisionContext(run.parsed);
        const context = out?.additionalContext;
        if (context) {
          const content = Array.isArray(event.content) ? event.content : [];
          return {
            content: [
              ...content,
              { type: "text", text: context },
            ],
          };
        }
      }
      return undefined;
    });
  }

  /* ---------------------------------------------------------------- */
  /* Adapter 4: agent_settled -> dcs_stop.py (best-effort)             */
  /*                                                                    */
  /* Pi has no "block a turn from ending" seam; the Stop hook's {block}  */
  /* is approximated by injecting a follow-up message that triggers one  */
  /* more turn. This is bounded by the hook's own MAX_STOP_BLOCKS=2      */
  /* counter (per project + session), so it cannot loop unbounded.      */
  /* ---------------------------------------------------------------- */
  if (stopEnabled) {
    pi.on("agent_settled", async (_event, ctx) => {
      const adapterId = "stop";
      const root = resolveProjectRoot(undefined, ctx.cwd);
      if (!root) return;

      const script = resolveHookScript(root, "dcs_stop.py");
      const run = await runHook(
        adapterId,
        script,
        {
          session_id: ctx.sessionManager?.getSessionId?.() ?? "unknown-session",
          cwd: ctx.cwd,
        },
        root,
      );
      if (run.outcome !== "ok") return;
      const parsed = run.parsed as { decision?: string; reason?: string } | null;
      if (!parsed || typeof parsed !== "object") return;
      if (parsed.decision !== "block") return;

      pi.sendMessage(
        {
          customType: "dcs-stop",
          content: String(parsed.reason || ""),
          display: true,
        },
        { deliverAs: "followUp", triggerTurn: true },
      );
    });
  }
}
