// src/cli/commands/ft-uninstall.ts
import { existsSync, readFileSync, writeFileSync, unlinkSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { paths } from "../../lifecycle/paths.ts";
import { readSnapshot } from "../../install/snapshot.ts";
import { removeClaudeIntegration } from "../../install/claude.ts";

function newestSnapshot(): string | null {
  const dir = join(paths.root(), "state", "install-snapshots", "claude");
  if (!existsSync(dir)) return null;
  const files = readdirSync(dir).filter((f) => f.endsWith(".json")).sort();
  if (files.length === 0) return null;
  return join(dir, files[files.length - 1]!);
}

export async function cmdFtUninstall(_positional: string[], verbose: boolean): Promise<number> {
  const settingsPath = join(paths.home(), ".claude", "settings.json");
  if (!existsSync(settingsPath)) { console.log("err=no-settings-json"); return 1; }
  const cfg = JSON.parse(readFileSync(settingsPath, "utf8")) as Record<string, unknown>;

  // 1. Remove env.ANTHROPIC_BASE_URL.
  const env = (cfg.env ?? {}) as Record<string, unknown>;
  delete env.ANTHROPIC_BASE_URL;
  if (Object.keys(env).length === 0) delete cfg.env;
  else cfg.env = env;

  // 2. Remove FT's hook entries.
  const ftPreBash = join(paths.home(), ".fewtok", "hooks", "pre-bash");
  const ftSessionStart = join(paths.home(), ".fewtok", "hooks", "session-start");
  const hooks = (cfg.hooks ?? {}) as any;
  if (Array.isArray(hooks.SessionStart)) {
    hooks.SessionStart = hooks.SessionStart
      .map((e: any) => ({ ...e, hooks: (e.hooks ?? []).filter((h: any) => h.command !== ftSessionStart) }))
      .filter((e: any) => e.hooks.length > 0);
  }
  if (Array.isArray(hooks.PreToolUse)) {
    hooks.PreToolUse = hooks.PreToolUse
      .map((e: any) => ({ ...e, hooks: (e.hooks ?? []).filter((h: any) => h.command !== ftPreBash) }))
      .filter((e: any) => e.hooks.length > 0);
  }
  cfg.hooks = hooks;

  // 3. Restore snapshot deletions.
  const snapPath = newestSnapshot();
  const snap = snapPath ? readSnapshot(snapPath) : null;
  if (snap) {
    for (const d of snap.deleted) {
      if (d.path[0] !== "hooks") continue;
      const top = (cfg.hooks ??= {} as any) as any;
      if (d.path[1] === "SessionStart" && d.entry) {
        top.SessionStart = top.SessionStart ?? [];
        top.SessionStart.push(d.entry);
      } else if (d.path[1] === "PreToolUse" && d.block) {
        top.PreToolUse = top.PreToolUse ?? [];
        top.PreToolUse.push(d.block);
      } else if (d.path[1] === "PreToolUse" && d.path[2] === "Bash" && d.entry) {
        top.PreToolUse = top.PreToolUse ?? [];
        let bash = top.PreToolUse.find((e: any) => e.matcher === "Bash");
        if (!bash) { bash = { matcher: "Bash", hooks: [] }; top.PreToolUse.push(bash); }
        bash.hooks.push(d.entry);
      }
    }
  }

  writeFileSync(settingsPath, JSON.stringify(cfg, null, 2) + "\n");

  // 4. Delete snapshot file.
  if (snapPath && existsSync(snapPath)) unlinkSync(snapPath);

  // 5. Restore ctx-mode integration (patch removal + gate hook restore from receipt).
  try {
    removeClaudeIntegration(settingsPath, paths.home());
  } catch (err) {
    if (verbose) console.warn(`ctx-integration restore: ${err instanceof Error ? err.message : String(err)}`);
    // Non-fatal — continue uninstall even if ctx receipt is missing
  }

  if (verbose) console.log("FT uninstalled. Restart claude. Pre-FT state restored.");
  else console.log("ok restart-claude");
  return 0;
}
