import { mkdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { atomicWriteFile } from "../../config/atomic-write";
import { assertNotRealClaudeConfigUnderTest } from "../../lib/test-home-guard";
import { claudeConfigDir } from "../auth-detect";
import { invalidateClaudeCodeServedCatalog } from "./cli-catalog";
import {
  invalidateNoProxyReceipt,
  mergeClaudeInterceptNoProxy,
  noProxyCoversLoopback,
  noProxyMergeable,
  noProxyReceiptPath,
  readNoProxyReceipt,
  readNoProxyReceiptBytes,
  serializeNoProxyReceipt,
  writeNoProxyReceiptBytes,
} from "./settings-no-proxy";

export { CLAUDE_INTERCEPT_LOOPBACK_NO_PROXY, mergeClaudeInterceptNoProxy } from "./settings-no-proxy";

/**
 * Claude Code `settings.json` env block for intercept mode.
 *
 * Both the Claude Desktop Code tab and the standalone `claude` CLI read the user
 * `~/.claude/settings.json` and export its `env` map into the process before any network
 * call. Two keys make every Claude Code process route through the local CONNECT proxy while
 * the app itself stays a first-party install:
 *
 *   env.HTTPS_PROXY         = http://opencodex:<token>@127.0.0.1:<proxy port>
 *   env.NODE_EXTRA_CA_CERTS = <configDir>/claude-intercept/ca.pem
 *
 * A third key keeps loopback off that proxy. Claude Code otherwise sends local HTTP MCP traffic
 * (`POST http://127.0.0.1:<port>/mcp`) through it, and the proxy only tunnels CONNECT to
 * non-loopback hosts, so every loopback MCP server failed with a 405 (#6936):
 *
 *   env.NO_PROXY            = <user entries>,127.0.0.1,localhost,::1,0.0.0.0
 *
 * Ownership is tracked by value, never by a marker key. The CA path is the anchor: it lives
 * under opencodex's own config directory, so only a block whose `NODE_EXTRA_CA_CERTS` names
 * that file is treated as ours. A user's own proxy or CA setting is left alone.
 *
 * `NO_PROXY` is shared with the user. Apply appends only the missing loopback entries and leaves
 * a covering value (including `*`) alone; removal puts back exactly what was there before, using
 * the receipt described in ./settings-no-proxy.ts, and otherwise preserves the current value.
 * A non-string `NO_PROXY` other than null is not one opencodex can extend: the block stays stale
 * and apply refuses with `foreign_env` instead of rewriting it.
 */

export const CLAUDE_INTERCEPT_MANAGED_ENV = ["HTTPS_PROXY", "NODE_EXTRA_CA_CERTS"] as const;
export type ClaudeInterceptManagedEnv = typeof CLAUDE_INTERCEPT_MANAGED_ENV[number];

export interface ClaudeInterceptEnv {
  HTTPS_PROXY: string;
  NODE_EXTRA_CA_CERTS: string;
}

export function claudeInterceptProxyUrl(port: number, authToken: string): string {
  return `http://opencodex:${encodeURIComponent(authToken)}@127.0.0.1:${port}`;
}

export function buildClaudeInterceptEnv(proxyPort: number, caCertPath: string, authToken: string): ClaudeInterceptEnv {
  return { HTTPS_PROXY: claudeInterceptProxyUrl(proxyPort, authToken), NODE_EXTRA_CA_CERTS: caCertPath };
}

export type ClaudeInterceptSettingsState =
  | { kind: "absent" }
  | { kind: "applied"; env: ClaudeInterceptEnv }
  | { kind: "stale"; env: Partial<ClaudeInterceptEnv> }
  | { kind: "foreign"; env: Partial<Record<ClaudeInterceptManagedEnv, string>> }
  | { kind: "unreadable"; path: string };

type SettingsDoc = Record<string, unknown> & { env?: Record<string, unknown> };

function settingsPath(configDir: string): string {
  return join(configDir, "settings.json");
}

function readSettings(path: string): { doc: SettingsDoc } | { error: "missing" | "unreadable" } {
  let raw: string;
  try {
    raw = readFileSync(path, "utf8");
  } catch (error) { // no-excuse-ok: catch -- an absent settings file is the fresh-install state.
    return { error: (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "unreadable" };
  }
  try {
    const parsed = JSON.parse(raw) as unknown;
    if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { error: "unreadable" };
    return { doc: parsed as SettingsDoc };
  } catch { // no-excuse-ok: catch -- a corrupt settings file must be reported, not overwritten.
    return { error: "unreadable" };
  }
}

function envRecord(doc: SettingsDoc): Record<string, unknown> {
  return doc.env && typeof doc.env === "object" && !Array.isArray(doc.env) ? doc.env : {};
}

/** Loopback proxy URLs are the only shape opencodex ever writes. */
export function isClaudeInterceptProxyUrl(value: unknown): value is string {
  return typeof value === "string" && /^http:\/\/(?:opencodex:[^@/]+@)?127\.0\.0\.1:\d{1,5}\/?$/.test(value.trim());
}

function isOwnedCaPath(value: unknown, ownedCaPath: string): value is string {
  return typeof value === "string" && value.trim() === ownedCaPath;
}

function setOrDelete(env: Record<string, unknown>, key: string, value: unknown): void {
  if (value === undefined) delete env[key];
  else env[key] = value;
}

/** Classify the current settings env against the values this router would write. */
export function inspectClaudeInterceptSettings(
  expected: ClaudeInterceptEnv,
  configDir = claudeConfigDir(),
): ClaudeInterceptSettingsState {
  const path = settingsPath(configDir);
  const read = readSettings(path);
  if ("error" in read) return read.error === "missing" ? { kind: "absent" } : { kind: "unreadable", path };
  const env = envRecord(read.doc);
  const proxy = env.HTTPS_PROXY;
  const ca = env.NODE_EXTRA_CA_CERTS;
  if (proxy === undefined && ca === undefined) return { kind: "absent" };
  // An owned block that still routes loopback into the proxy is stale, so the startup migrate
  // and every reconcile repair installs written before the bypass existed.
  if (proxy === expected.HTTPS_PROXY && ca === expected.NODE_EXTRA_CA_CERTS && noProxyCoversLoopback(env.NO_PROXY)) {
    return { kind: "applied", env: expected };
  }
  const caOurs = isOwnedCaPath(ca, expected.NODE_EXTRA_CA_CERTS);
  const proxyOurs = proxy === undefined || isClaudeInterceptProxyUrl(proxy);
  if (caOurs && proxyOurs) {
    return {
      kind: "stale",
      env: {
        ...(typeof proxy === "string" ? { HTTPS_PROXY: proxy } : {}),
        ...(typeof ca === "string" ? { NODE_EXTRA_CA_CERTS: ca } : {}),
      },
    };
  }
  return {
    kind: "foreign",
    env: {
      ...(typeof proxy === "string" ? { HTTPS_PROXY: proxy } : {}),
      ...(typeof ca === "string" ? { NODE_EXTRA_CA_CERTS: ca } : {}),
    },
  };
}

const defaultPersist = (path: string, content: string): void => atomicWriteFile(path, content);
let persistFile = defaultPersist;

/** Replace the settings.json write in tests; the real-home guard still runs first. Returns a restore. */
export function setClaudeSettingsPersistForTests(persist: (path: string, content: string) => void): () => void {
  const before = persistFile;
  persistFile = persist;
  return () => { persistFile = before; };
}

/** Commit settings.json. Once this returns, the file on disk holds the new document. */
function persistSettings(path: string, doc: SettingsDoc): void {
  // An armed test process must not rewrite the real Claude settings.json (#6775).
  assertNotRealClaudeConfigUnderTest(dirname(path), path);
  mkdirSync(dirname(path), { recursive: true });
  // The managed env embeds the proxy token, so the file must stay owner-only:
  // atomicWriteFile applies the real NTFS ACL on Windows where chmod is a no-op.
  persistFile(path, `${JSON.stringify(doc, null, 2)}\n`);
}

function writeSettings(path: string, doc: SettingsDoc): void {
  persistSettings(path, doc);
  // Whether Claude Code reaches the proxy just changed, so its cached /model list is stale.
  invalidateClaudeCodeServedCatalog(dirname(path));
}

export type ClaudeInterceptSettingsWrite =
  | { ok: true; changed: boolean; path: string }
  | { ok: false; reason: "unreadable" | "foreign_env"; path: string };

/** Capture only the managed keys. Rollback preserves unrelated edits and refuses
 * to overwrite a newer proxy/CA choice made after this apply. */
export function captureClaudeInterceptSettingsRollback(
  expected: ClaudeInterceptEnv | (() => ClaudeInterceptEnv),
  configDir = claudeConfigDir(),
): () => boolean {
  const path = settingsPath(configDir);
  const before = readSettings(path);
  if ("error" in before && before.error !== "missing") return () => false;
  const previous = "doc" in before ? { ...envRecord(before.doc) } : {};
  const previousReceipt = readNoProxyReceiptBytes(configDir);
  // What apply writes over the captured value; rollback restores NO_PROXY only while it still
  // holds exactly that, so a user edit made after the apply survives. The receipt is restored
  // with it, because it describes that value.
  const appliedNoProxy = mergeClaudeInterceptNoProxy(previous.NO_PROXY) ?? previous.NO_PROXY;
  return () => {
    try {
      assertNotRealClaudeConfigUnderTest(configDir, path, noProxyReceiptPath(configDir));
      const target = typeof expected === "function" ? expected() : expected;
      const current = readSettings(path);
      if (!("doc" in current)) return false;
      const env = envRecord(current.doc);
      if (CLAUDE_INTERCEPT_MANAGED_ENV.some(key => env[key] !== target[key])) return false;
      for (const key of CLAUDE_INTERCEPT_MANAGED_ENV) {
        setOrDelete(env, key, previous[key]);
      }
      const restoreNoProxy = env.NO_PROXY === appliedNoProxy;
      if (restoreNoProxy) setOrDelete(env, "NO_PROXY", previous.NO_PROXY);
      if (Object.keys(env).length === 0) delete current.doc.env;
      else current.doc.env = env;
      writeSettings(path, current.doc);
      if (restoreNoProxy) {
        if (previousReceipt === null) return invalidateNoProxyReceipt(configDir);
        writeNoProxyReceiptBytes(configDir, previousReceipt);
      }
      return true;
    } catch { return false; }
  };
}

/**
 * Write the intercept env into `settings.json`. Refuses when a managed key already holds a
 * value opencodex did not write (a user-configured corporate proxy, for instance), or when
 * NO_PROXY holds a non-string value opencodex cannot extend.
 */
export function applyClaudeInterceptSettings(
  env: ClaudeInterceptEnv,
  configDir = claudeConfigDir(),
): ClaudeInterceptSettingsWrite {
  const path = settingsPath(configDir);
  const state = inspectClaudeInterceptSettings(env, configDir);
  if (state.kind === "unreadable") return { ok: false, reason: "unreadable", path };
  if (state.kind === "foreign") return { ok: false, reason: "foreign_env", path };
  if (state.kind === "applied") return { ok: true, changed: false, path };
  const read = readSettings(path);
  const doc: SettingsDoc = "doc" in read ? read.doc : {};
  const current = envRecord(doc);
  if (!noProxyMergeable(current.NO_PROXY)) return { ok: false, reason: "foreign_env", path };
  const noProxy = mergeClaudeInterceptNoProxy(current.NO_PROXY);
  // A new ownership episode, or a new NO_PROXY value, makes any existing receipt describe the
  // wrong value. Drop it before writing, and write nothing when it cannot be dropped.
  if ((state.kind === "absent" || noProxy !== null) && !invalidateNoProxyReceipt(configDir)) {
    return { ok: false, reason: "unreadable", path: noProxyReceiptPath(configDir) };
  }
  doc.env = { ...current, ...env, ...(noProxy === null ? {} : { NO_PROXY: noProxy }) };
  writeSettings(path, doc);
  if (noProxy !== null) {
    const receipt = { version: 1 as const, hadKey: "NO_PROXY" in current, previous: typeof current.NO_PROXY === "string" ? current.NO_PROXY : null, written: noProxy };
    // Without a receipt, removal keeps the appended entries: the harmless direction.
    try { writeNoProxyReceiptBytes(configDir, serializeNoProxyReceipt(receipt)); } catch { /* no provenance */ }
  }
  return { ok: true, changed: true, path };
}

/**
 * Rewrite an env block opencodex already owns when it no longer matches what this run
 * would write — a pre-auth `http://127.0.0.1:<port>` left behind by an upgrade would get
 * a 407 from the now-authenticated proxy until `ocx ensure` or an apply ran. Unlike apply
 * this never creates an absent env: only `stale` (owned) state is rewritten, so the
 * runtime can call it on every start without enabling the integration for anyone else.
 */
export function migrateClaudeInterceptSettings(
  env: ClaudeInterceptEnv,
  configDir = claudeConfigDir(),
): ClaudeInterceptSettingsWrite {
  const path = settingsPath(configDir);
  const state = inspectClaudeInterceptSettings(env, configDir);
  if (state.kind === "unreadable") return { ok: false, reason: "unreadable", path };
  if (state.kind === "foreign") return { ok: false, reason: "foreign_env", path };
  if (state.kind !== "stale") return { ok: true, changed: false, path };
  return applyClaudeInterceptSettings(env, configDir);
}

/**
 * Remove the managed keys and put NO_PROXY back as it was, but only the values opencodex owns.
 * The receipt is dropped before the settings write; when that fails nothing is changed, so a
 * receipt can never outlive the episode it describes.
 */
export function removeClaudeInterceptSettings(
  ownedCaPath: string,
  configDir = claudeConfigDir(),
): ClaudeInterceptSettingsWrite {
  const path = settingsPath(configDir);
  const read = readSettings(path);
  if ("error" in read) {
    return read.error === "missing" ? { ok: true, changed: false, path } : { ok: false, reason: "unreadable", path };
  }
  const env = envRecord(read.doc);
  if (!isOwnedCaPath(env.NODE_EXTRA_CA_CERTS, ownedCaPath)) return { ok: true, changed: false, path };
  const receipt = readNoProxyReceipt(configDir);
  const receiptBytes = readNoProxyReceiptBytes(configDir);
  delete env.NODE_EXTRA_CA_CERTS;
  if (isClaudeInterceptProxyUrl(env.HTTPS_PROXY)) delete env.HTTPS_PROXY;
  if (receipt && env.NO_PROXY === receipt.written) setOrDelete(env, "NO_PROXY", receipt.hadKey ? receipt.previous : undefined);
  if (!invalidateNoProxyReceipt(configDir)) return { ok: false, reason: "unreadable", path: noProxyReceiptPath(configDir) };
  if (Object.keys(env).length === 0) delete read.doc.env;
  else read.doc.env = env;
  try {
    persistSettings(path, read.doc);
  } catch (error) {
    // A removal that was not committed has not ended the episode, so its receipt stays valid. Only the
    // persist step is covered: once settings.json changed, the receipt must not come back.
    if (receiptBytes !== null) {
      try { writeNoProxyReceiptBytes(configDir, receiptBytes); } catch { /* keep the original error */ }
    }
    throw error;
  }
  invalidateClaudeCodeServedCatalog(dirname(path));
  return { ok: true, changed: true, path };
}
