// src/cli/commands/ft-check.ts
// Inverted check (2026-05-22): healthy state = ~dist/server/wrangler.jsonY CLEAN of ft entries.
// See CLAUDE.md "no-global-settings-injection". Per-session activation only.
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { paths } from "../../lifecycle/paths.ts";
import { readProxyPort } from "./_session.ts";

export async function cmdFtCheck(_positional: string[], verbose: boolean): Promise<number> {
  const findings: Array<{ ok: boolean; msg: string }> = [];

  // ── Proxy daemon ──
  const port = readProxyPort();
  findings.push({ ok: port !== null, msg: port !== null ? `port=${port}` : "port-file-missing" });
  if (port !== null) {
    try {
      const r = await fetch(`http://127.0.0.1:${port}/_ft/status`);
      findings.push({ ok: r.ok, msg: r.ok ? "proxy-responding" : `proxy-status-${r.status}` });
    } catch { findings.push({ ok: false, msg: "proxy-unreachable" }); }
  }

  // ── settings.json cleanliness (inverted: presence = error) ──
  const settingsPath = join(paths.home(), ".claude", "settings.json");
  if (existsSync(settingsPath)) {
    const cfg = JSON.parse(readFileSync(settingsPath, "utf8")) as Record<string, unknown>;
    const env = (cfg.env ?? {}) as Record<string, unknown>;
    if (env.ANTHROPIC_BASE_URL) {
      findings.push({ ok: false, msg: `env-anthropic-base-url-present=${env.ANTHROPIC_BASE_URL}` });
    } else {
      findings.push({ ok: true, msg: "env-clean" });
    }
    const hooks = (cfg.hooks ?? {}) as Record<string, unknown>;
    const ftPreBash = join(paths.home(), ".fewtok", "hooks", "pre-bash");
    const ftSessionStart = join(paths.home(), ".fewtok", "hooks", "session-start");
    const ss = (hooks["SessionStart"] ?? []) as Array<{ hooks?: Array<{ command?: string }> }>;
    const ptu = (hooks["PreToolUse"] ?? []) as Array<{ hooks?: Array<{ command?: string }> }>;
    const ftHook = [...ss, ...ptu].some((e) =>
      (e.hooks ?? []).some((h) => h.command === ftPreBash || h.command === ftSessionStart),
    );
    findings.push(
      ftHook
        ? { ok: false, msg: "ft-hooks-present (run: fewtok uninstall)" }
        : { ok: true, msg: "ft-hooks-absent" },
    );
  } else {
    findings.push({ ok: true, msg: "settings-json-absent" });
  }

  // ── cld wrapper presence (the only valid activation path) ──
  const cldCandidates = [
    join(paths.home(), ".local", "bin", "cld"),
    join(paths.home(), "Projects", "fewtok", "bin", "cld"),
  ];
  const cldExists = cldCandidates.some((p) => existsSync(p));
  findings.push({ ok: cldExists, msg: cldExists ? "cld-wrapper-found" : "cld-wrapper-missing" });

  const allOk = findings.every((f) => f.ok);
  if (verbose) {
    for (const f of findings) console.log(`${f.ok ? "✓" : "✗"} ${f.msg}`);
  } else {
    console.log(findings.map((f) => `${f.ok ? "ok" : "err"}=${f.msg.split(" ")[0]}`).join(" "));
  }
  return allOk ? 0 : 1;
}
