import { readFileSync, writeFileSync } from "node:fs";
import { clearCodexAccountPin } from "../codex/account-priority";
import { getConfigPath, mutatePersistedConfig, readConfigDiagnostics, sanitizeModelCostsForDisplay, saveConfig, validateConfigCandidate, withConfigMutationLockSync } from "../config";
import { MALFORMED_CODEX_AUTH_METHOD_WARNING } from "../config/load-degrade";
import { readClientConnectionState } from "../client/state";
import { getConfigDir, withConfigDirHardeningSettled } from "../config/paths";
import { readCliConfigForMutation } from "./config-mutation";
import { VISION_REASONING_EFFORTS, isVisionReasoningEffort } from "../reasoning-effort";
import type { OcxConfig } from "../types";
import { normalizeVisionReasoningForModel } from "../vision/reasoning";
import type { ServiceApiTokenState } from "../lib/service-secrets";
import { redactUrlForLog } from "../lib/redact";
import { CliUsageError, printData, rejectArgs, runCliAction, takeFlag } from "./runtime-api";

const USAGE = `Usage:
  ocx config [show] [--json] [--source]
  ocx config get <dot.path> [--json]
  ocx config set <dot.path> <json-or-string> [--json]
  ocx config unset <dot.path> [--json]
  ocx config validate [path|-] [--json]
  ocx config export <path|-> [--json]
  ocx config import <path|-> --yes [--json]
Entering v2-plaintext requires: ocx v2 mode v2-plaintext --acknowledge-plaintext-agent-messages`;

/**
 * Keys whose VALUE is a credential and must never be printed by display commands.
 * `config export` writes the raw config so an export can restore credentials; it does
 * not call `redact`.
 *
 * URL-valued credentials must be named explicitly: `webhookUrl` matches none of the
 * other patterns, and a proxy URL's userinfo is handled by the `proxy` branch in
 * `redact` rather than by masking the whole value.
 */
const SECRET_KEYS = /^(apiKey|key|accessToken|refreshToken|idToken|token|password|clientSecret|webhookUrl)$/i;
const BLOCKED_SEGMENTS = new Set(["__proto__", "prototype", "constructor"]);

/**
 * The synthetic `_remoteHub` note printed by `ocx config show` on a client (#4236).
 *
 * `runtimeRole: "client"` and the `client` block were already printed, and were already ignored:
 * an agent read a client's `config.json`, saw an empty `providers` map and no grok, and concluded
 * the hub could not serve grok. Naming the situation in the config output costs one key.
 *
 * `connected` is OBSERVED, never assumed. It was briefly hardcoded `true` for any config with a
 * `client` block, which is the same defect in miniature: the presence of configuration is not
 * evidence that the connection works, and a machine whose data-plane token was revoked, rotated
 * away or deleted would have been labelled `connected: true` while it could not reach the hub at
 * all. The read-only projection compares the bounded token file's fingerprint against the
 * connection record, and passes that answer in so this formatter stays pure and testable.
 *
 * Synthetic and NOT persisted, for two reasons. `clientConnectionSchema` is `.strict()`, so a
 * `client.note` field would not validate; and persisted prose drifts from the behaviour it
 * describes. The leading underscore marks it as an annotation rather than a setting, and
 * `config export` emits the real config untouched so round-trips still validate.
 */
export function remoteHubConfigNote(
  config: OcxConfig,
  readConnection: () => RemoteHubConnectionObservation,
): { connected: boolean; origin: string; note: string } | null {
  if (config.runtimeRole !== "client" || !config.client) return null;
  // A thunk, so a standalone or hub install pays nothing: the guard above returns first and the
  // connection probe (three file reads) never runs.
  const connection = readConnection();
  // Both halves are required: a settled connection record AND the token it recorded. Either one
  // alone describes a machine that cannot read its hub, and `ocx status` is still the command
  // that has the facts — so the note points there in every case, connected or not.
  const connected = connection.state === "connected" && connection.token === "owned";
  const link = config.client.transport === "link";
  const note = connection.state !== "connected"
    ? `this machine is configured as a client but its connection is ${connection.state}${connection.reason ? ` (${connection.reason})` : ""}; run ocx connect status`
    : connection.token !== "owned"
      ? `this machine is configured as a client but its ${link ? "Remote Link key" : "hub data-plane token"} is ${connection.token}; run ocx connect status`
      : link
        ? "this machine is a Remote Link Child: provider credentials, model availability and the Codex settings OpenCodex writes come from its Home; the settings in this file are local and inactive while linked; run ocx status"
        : "provider credentials and model availability live on the hub; run ocx status";
  return { connected, origin: config.client.serverUrl, note };
}

export type RemoteHubConnectionObservation = {
  state: "disconnected" | "connected" | "invalid" | "mismatched";
  reason?: string;
  token: "owned" | "missing" | "changed" | "unsafe";
};

export function remoteHubConnectionFromTokenState(
  config: Pick<OcxConfig, "client">,
  tokenState: ServiceApiTokenState,
): RemoteHubConnectionObservation {
  const token = tokenState.kind === "absent"
    ? "missing"
    : tokenState.kind === "unsafe"
      ? "unsafe"
      : tokenState.fingerprint === config.client?.tokenFingerprint ? "owned" : "changed";
  return { state: "connected", token };
}

async function readRemoteHubConfigNote(config: OcxConfig): Promise<ReturnType<typeof remoteHubConfigNote>> {
  if (config.runtimeRole !== "client" || !config.client) return null;
  // This display command needs only connection ownership, not lifecycle recovery, catalog
  // readiness, or any write-capable connect machinery. Keep the read on the bounded token
  // observer so a cold `config show` never imports the full connect command graph.
  const { readServiceApiTokenState } = await import("../lib/service-secrets");
  return remoteHubConfigNote(
    config,
    () => remoteHubConnectionFromTokenState(config, readServiceApiTokenState()),
  );
}

function redact(value: unknown, key = ""): unknown {
  if (key === "proxy" && typeof value === "string") {
    // "direct" and credential-less proxy URLs carry no secret and stay readable; only a
    // URL with userinfo is masked, and then only its credentials — host and port stay
    // visible so the output still says WHERE traffic goes. A non-URL value that is not
    // "direct" cannot be proven credential-free, so it is masked whole.
    if (!value || value === "direct") return value;
    try {
      const parsed = new URL(value);
      return parsed.username || parsed.password ? redactUrlForLog(value) : value;
    } catch {
      return "********";
    }
  }
  if (SECRET_KEYS.test(key) && typeof value === "string") return value ? "********" : value;
  // `client.priorCatalog` is the base64 catalog snapshot connect took before overwriting the
  // local one — up to 64 MB of it (src/config.ts). Printed in full it buried `runtimeRole` and
  // the `client` block under a wall of base64, which is how a reader came to miss that this
  // machine is a client at all. Size only, mirroring sanitizeModelCostsForDisplay.
  if (key === "priorCatalog" && typeof value === "string") {
    return value ? `<omitted: ${Buffer.byteLength(value)} bytes>` : value;
  }
  // modelCosts rows are keyed by model id; a pasted API key in a key position
  // must not be echoed back by config show/get (values are already redacted).
  if (key === "modelCosts") return sanitizeModelCostsForDisplay(value);
  if (Array.isArray(value)) return value.map(item => redact(item));
  if (value && typeof value === "object") {
    return Object.fromEntries(Object.entries(value as Record<string, unknown>).map(([childKey, child]) => [childKey, redact(child, childKey)]));
  }
  return value;
}

function pathSegments(path: string): string[] {
  const segments = path.split(".").map(part => part.trim()).filter(Boolean);
  if (segments.length === 0 || segments.some(part => BLOCKED_SEGMENTS.has(part))) throw new CliUsageError("invalid config path", USAGE);
  return segments;
}

/**
 * #8319: `config set` writes the file, but a running proxy keeps checking pairing and CORS origins
 * against the config it is running with. `hub` is live topology and is applied only at start, including the
 * management listener (`hub.managementIngress`)
 * (`LIVE_TOPOLOGY_KEYS`); `corsAllowOrigins` reaches the running config only when some later live
 * save adopts the file. Saying only "Set <path>." left an operator retrying a refused
 * `ocx hub invite` against the old list. `codexAuthMethod` (#8082) is read from the running config by the
 * Codex login route, so a device-only policy set here would not stop a browser login until a restart.
 * Limited to these keys, so the note never claims a restart
 * that is not needed.
 */
export function startupOnlyConfigNotes(path: string): string[] {
  const segments = pathSegments(path);
  if (segments[0] === "corsAllowOrigins") {
    return ["A running OpenCodex may keep using its previous corsAllowOrigins until it restarts; restart it to apply the new value now."];
  }
  if (segments[0] === "hub" && (segments.length === 1 || segments[1] === "managementPublicOrigin" || segments[1] === "managementIngress")) {
    return [`A running OpenCodex applies ${segments.join(".")} only when it starts; restart it to use the new value.`];
  }
  if (segments[0] === "codexAuthMethod") {
    return ["A running OpenCodex keeps its previous codexAuthMethod for Codex pool account logins until it restarts; restart it to apply the new value now."];
  }
  return [];
}

function getPath(root: unknown, path: string): unknown {
  let current = root;
  for (const segment of pathSegments(path)) {
    if (!current || typeof current !== "object" || !Object.hasOwn(current, segment)) throw new CliUsageError(`config path not found: ${path}`);
    current = (current as Record<string, unknown>)[segment];
  }
  return current;
}

function setPath(root: Record<string, unknown>, path: string, value: unknown, remove = false): void {
  const segments = pathSegments(path);
  let current = root;
  for (const segment of segments.slice(0, -1)) {
    const next = current[segment];
    if (!next || typeof next !== "object" || Array.isArray(next)) throw new CliUsageError(`config parent path not found: ${segment}`, USAGE);
    current = next as Record<string, unknown>;
  }
  const leaf = segments.at(-1)!;
  if (remove && !Object.hasOwn(current, leaf)) throw new CliUsageError(`config path not found: ${path}`);
  if (remove) delete current[leaf];
  else current[leaf] = value;
}

/** Interpret config-set input as JSON when valid, otherwise preserve it as a string. */
function parseValue(raw: string): unknown {
  try { return JSON.parse(raw); }
  catch { return raw; }
}

/** Accept one UTF-8 BOM from Windows JSON files or piped input. */
function loadInput(path: string): unknown {
  const raw = path === "-" ? readFileSync(0, "utf8") : readFileSync(path, "utf8");
  try { return JSON.parse(raw.replace(/^\uFEFF/, "")); }
  catch { throw new CliUsageError(`invalid JSON in ${path}`); }
}

function visionReasoningError(value: unknown): string | null {
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
  const vision = (value as Record<string, unknown>).visionSidecar;
  if (!vision || typeof vision !== "object" || Array.isArray(vision)) return null;
  const reasoning = (vision as Record<string, unknown>).reasoning;
  if (reasoning === undefined || isVisionReasoningEffort(reasoning)) return null;
  return `schema_invalid: visionSidecar.reasoning: must be one of ${VISION_REASONING_EFFORTS.join(", ")}`;
}

function validateCandidate(value: unknown): ReturnType<typeof validateConfigCandidate> {
  const error = visionReasoningError(value);
  return error ? { ok: false, error } : validateConfigCandidate(value);
}

function normalizeVisionConfig(config: OcxConfig): OcxConfig {
  const vision = config.visionSidecar;
  if (!vision || vision.reasoning === undefined) return config;
  // Keep CLI import/set semantics aligned with the execution path: an omitted or blank model means
  // the bounded OpenAI vision default, gpt-5.6-luna, not the Dashboard's web-search default.
  const model = vision.model || "gpt-5.6-luna";
  const normalized = normalizeVisionReasoningForModel(model, vision.reasoning);
  if (normalized === undefined) delete vision.reasoning;
  else vision.reasoning = normalized;
  return config;
}

function validate(value: unknown): OcxConfig {
  const result = validateCandidate(value);
  if (!result.ok) throw new CliUsageError(result.error);
  return normalizeVisionConfig(result.config);
}

function requireDedicatedPlaintextTransition(current: OcxConfig, candidate: OcxConfig): void {
  if (candidate.multiAgentMode === "v2-plaintext" && current.multiAgentMode !== "v2-plaintext") {
    throw new CliUsageError("Entering v2-plaintext requires ocx v2 mode v2-plaintext --acknowledge-plaintext-agent-messages. Task text may remain in history, provider requests and debug state. Complete that transition before restoring a config with this mode.");
  }
}

export async function handleConfigCommand(argv: string[]): Promise<number> {
  let outcome = 0;
  const status = await runCliAction(async () => {
    const args = [...argv];
    const wantsJson = takeFlag(args, "--json");
    const source = takeFlag(args, "--source");
    if (args.includes("--json") || args.includes("--source")) throw new CliUsageError("config flags may only be specified once", USAGE);
    const action = (args.shift() ?? "show").toLowerCase();
    if (source && action !== "show") throw new CliUsageError("--source is only supported for config show", USAGE);
    if (action === "show") {
      rejectArgs(args, USAGE);
      const diagnostics = readConfigDiagnostics();
      if (diagnostics.source === "fallback" || diagnostics.error) {
        console.error(`Warning: Config at ${getConfigPath()} is invalid or unreadable; defaults are being shown for invalid settings. Run: ocx config validate. Inspect: ocx config show --source.`);
        if (!source) outcome = 1;
      }
      const redacted = redact(diagnostics.config);
      const note = await readRemoteHubConfigNote(diagnostics.config);
      // First key, not last: it has to be read before the empty `providers` map that misled a
      // reader into concluding nothing was configured anywhere.
      const config = note && redacted && typeof redacted === "object" && !Array.isArray(redacted)
        ? { _remoteHub: note, ...redacted as Record<string, unknown> }
        : redacted;
      const result = source ? { config, source: diagnostics.source, error: diagnostics.error, warnings: diagnostics.warnings ?? [] } : config;
      printData(result, true);
      return;
    }
    if (action === "get") {
      const path = args.shift();
      if (!path) throw new CliUsageError("config path is required", USAGE);
      rejectArgs(args, USAGE);
      await (await import("./link-child")).printLinkChildLocalNotice("The values");
      const diagnostics = readConfigDiagnostics();
      if (diagnostics.source === "fallback" || diagnostics.error) {
        console.error(`Warning: Config at ${getConfigPath()} is invalid or unreadable; defaults are being shown for invalid settings. Run: ocx config validate. Inspect: ocx config show --source.`);
        outcome = 1;
      }
      const value = redact(getPath(diagnostics.config, path), pathSegments(path).at(-1));
      if (wantsJson || typeof value === "object") console.log(JSON.stringify(value, null, 2));
      else console.log(String(value));
      return;
    }
    if (action === "set" || action === "unset") {
      await (await import("./link-child")).printLinkChildLocalWriteNotice();
      const path = args.shift();
      const raw = action === "set" ? args.shift() : undefined;
      if (!path || (action === "set" && raw === undefined)) throw new CliUsageError(action === "unset" ? "config path is required" : "config path and value are required", USAGE);
      rejectArgs(args, USAGE);
      if (pathSegments(path)[0] === "telemetry") {
        throw new CliUsageError("telemetry cannot be modified via ocx config; use `ocx telemetry enable` or `ocx telemetry disable`", USAGE);
      }
      // #1835/#1838: the read used to happen OUTSIDE the mutation lock, so a concurrent
      // edit landing between it and the save was reverted by this whole-snapshot write.
      // `mutatePersistedConfig` reruns this callback against the latest validated disk
      // state, so the operation is applied to what is actually there at commit time.
      let savedValue: unknown = null;
      const outcome = await withConfigDirHardeningSettled(getConfigDir(), () => mutatePersistedConfig(fresh => {
        // Snapshot BEFORE mutating: comparing after the write compares a value with
        // itself and would report every no-op as a change, bumping the generation.
        const before = JSON.stringify(fresh);
        const candidate = structuredClone(fresh) as unknown as Record<string, unknown>;
        setPath(candidate, path, raw === undefined ? undefined : parseValue(raw), action === "unset");
        const config = validate(candidate);
        requireDedicatedPlaintextTransition(fresh, config);
        savedValue = action === "unset" ? null : getPath(config, path);
        // Setting the order here is the operator restating it, exactly as through
        // `ocx account priority` or the management route, so it releases the manual pin
        // for the same reason those do: a pin made before any order existed would
        // otherwise outrank every order set afterwards, capping the pool at the pinned
        // account's tier with nothing on any surface explaining why. `import` is
        // deliberately not covered — that file supplies its own pin, so there is no
        // stale one to release.
        if (pathSegments(path)[0] === "codexAccountPriorities") clearCodexAccountPin(config);
        // REPLACE rather than merge: `Object.assign` alone cannot remove a key that
        // `unset` deleted, which would make unset silently succeed while changing nothing.
        for (const key of Object.keys(fresh)) {
          if (!(key in (config as unknown as Record<string, unknown>))) {
            delete (fresh as unknown as Record<string, unknown>)[key];
          }
        }
        Object.assign(fresh, config);
        return { changed: JSON.stringify(fresh) !== before, value: undefined };
      }));
      if (outcome.status === "unavailable") {
        throw new CliUsageError(outcome.reason === "conflict"
          ? "config changed while applying this update; retry"
          : `config is ${outcome.reason}`);
      }
      printData({ ok: true, path, value: redact(savedValue, pathSegments(path).at(-1)) }, wantsJson,
        [
          `${action === "unset" ? "Unset" : "Set"} ${path}.`,
          ...(outcome.status === "committed" ? startupOnlyConfigNotes(path) : []),
        ]);
      return;
    }
    if (action === "validate") {
      const path = args.shift();
      rejectArgs(args, USAGE);
      const diagnostics = path ? undefined : readConfigDiagnostics();
      const result = diagnostics?.error
        ? { ok: false as const, error: diagnostics.error }
        : validateCandidate(path ? loadInput(path) : diagnostics?.config);
      // General diagnostics can include file contents. Validate emits only the fixed policy warning.
      const warnings = diagnostics?.warnings?.includes(MALFORMED_CODEX_AUTH_METHOD_WARNING)
        ? [MALFORMED_CODEX_AUTH_METHOD_WARNING] : [];
      printData({
        ...(result.ok ? { ok: true, source: path ?? getConfigPath() } : result),
        ...(warnings.length ? { warnings } : {}),
      }, wantsJson, [
        result.ok ? (warnings.length ? "Config is usable with warnings." : "Config is valid.") : `Config is invalid: ${result.error}`,
        ...warnings.map(warning => `Warning: ${warning}`),
      ]);
      if (!result.ok) outcome = 1;
      return;
    }
    if (action === "export") {
      const path = args.shift();
      if (!path) throw new CliUsageError("export path is required", USAGE);
      rejectArgs(args, USAGE);
      const content = `${JSON.stringify(readConfigDiagnostics().config, null, 2)}\n`;
      if (path === "-") process.stdout.write(content);
      else {
        writeFileSync(path, content, { encoding: "utf8", mode: 0o600 });
        printData({ ok: true, path }, wantsJson, [`Exported config to ${path}.`]);
      }
      return;
    }
    if (action === "import") {
      await (await import("./link-child")).printLinkChildLocalWriteNotice();
      const path = args.shift();
      const yes = takeFlag(args, "--yes");
      if (!path) throw new CliUsageError("import path is required", USAGE);
      if (!yes) throw new CliUsageError("import requires --yes", USAGE);
      rejectArgs(args, USAGE);
      await withConfigDirHardeningSettled(getConfigDir(), () => {
        // Reject invalid authority before lock preparation creates coordination files.
        const current = readCliConfigForMutation();
        const rawInput = loadInput(path);
        if (rawInput && typeof rawInput === "object" && !Array.isArray(rawInput) && Object.hasOwn(rawInput, "telemetry")) {
          delete (rawInput as Record<string, unknown>).telemetry;
          console.warn("Note: ignored telemetry block during config import; use `ocx telemetry` to manage telemetry consent.");
        }
        const imported = validate(rawInput);
        // Do not hold the shared lock while reading stdin. Recheck the live mode and
        // the active client connection, then save in the same synchronous transaction;
        // saveConfig reuses this transaction.
        withConfigMutationLockSync(() => {
          const client = readClientConnectionState();
          if (client.kind === "connected" && (imported.runtimeRole !== "client"
            || JSON.stringify(imported.client) !== JSON.stringify(client.value))) {
            throw new Error("config import refused: disconnect the active client before replacing its connection");
          }
          const persistedTelemetry = readConfigDiagnostics({ passive: true }).config.telemetry ?? current.telemetry;
          if (persistedTelemetry !== undefined) {
            imported.telemetry = structuredClone(persistedTelemetry);
          } else {
            delete imported.telemetry;
          }
          requireDedicatedPlaintextTransition(readCliConfigForMutation(), imported);
          saveConfig(imported);
        });
      });
      printData({ ok: true, source: path }, wantsJson, [`Imported config from ${path}. Restart or run ocx sync if needed.`]);
      return;
    }
    throw new CliUsageError(`unknown config command ${action}`, USAGE);
  });
  return status || outcome;
}

export const CONFIG_USAGE = USAGE;
