import { publishCredentialSync } from "../local-credentials/generation";
import { osStoreAccounts } from "../local-credentials/references";
import { normalizeAccountAutoPauseRevisions, observeAccountAutoPauseRevisions, snapshotAutoPauseFingerprints } from "./account-auto-pause-revisions";
import { existsSync, readFileSync } from "node:fs";
import { configReasoningPinsConfigError } from "./provider-validation";
import type { OcxConfig } from "../types";
import { withPreservedDiskOnlyProviders } from "../usage/user-cost-overlays";
import { refreshConfigDerivedRegistries } from "./derived-registries";
import { atomicWriteFile, isMissingPathError } from "./atomic-write";
import { getConfigPath } from "./paths";
import { configRebaseDeletionKeys, projectConfigRebaseProvenance } from "./rebase-provenance";
import { clientConnectionSchema } from "./schema/leaf-validators";
import { projectRemovedOpenCodeFreeSnapshot } from "./removed-opencode-free-backup";

/** The requested bytes are current; callers must not roll back only live state. */
export class ConfigWritePublishedError extends Error {
  constructor(cause: unknown) {
    super("Config was published, but post-publication bookkeeping failed", { cause });
    this.name = "ConfigWritePublishedError";
  }
}

/** The literal file, with no schema merge or default injection; preserve-only leaves it unprojected. */
export function readRawConfigJson(projectRetired: boolean | "preserve-only" = false): Record<string, unknown> | undefined {
  let configPath: string;
  let bytes: Buffer;
  let parsed: unknown;
  try {
    configPath = getConfigPath();
    if (!existsSync(configPath)) return undefined;
    bytes = readFileSync(configPath);
    const raw = bytes.toString("utf-8").replace(/^\uFEFF/, "");
    parsed = JSON.parse(raw) as unknown;
    if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
  } catch {
    // Unreadable or corrupt: behave exactly as before. Never fail a save over protection.
    return undefined;
  }
  if (projectRetired === "preserve-only") {
    // Preservation is optional; its failure must not discard the parsed snapshot that the
    // client-state guard and OS-store reference accounting depend on.
    try {
      projectRemovedOpenCodeFreeSnapshot(structuredClone(parsed), { path: configPath, bytes });
    } catch {
      console.warn("[opencodex] Could not check config.json for retired OpenCode Free entries before saving; no recovery copy was made.");
    }
  } else if (projectRetired) {
    try {
      projectRemovedOpenCodeFreeSnapshot(parsed, { path: configPath, bytes });
    } catch {
      // The in-place projection may be partial; keep the previous unreadable result.
      return undefined;
    }
  }
  return parsed as Record<string, unknown>;
}

function failClosedClientPersistenceError(
  raw: Record<string, unknown> | undefined,
  candidate: OcxConfig,
): string | null {
  if (!raw) return null;
  const rawHasClient = Object.hasOwn(raw, "client") && raw.client !== undefined;
  const rawRole = raw.runtimeRole;
  const rawRoleValid = rawRole === undefined
    || rawRole === "standalone"
    || rawRole === "hub"
    || rawRole === "client";
  const rawClientValid = !rawHasClient || clientConnectionSchema.safeParse(raw.client).success;
  const rawPairValid = rawRoleValid
    && ((rawRole === "client" && rawHasClient && rawClientValid)
      || (rawRole !== "client" && !rawHasClient));
  if (rawPairValid) return null;

  const candidateValid = candidate.runtimeRole === "client"
    && clientConnectionSchema.safeParse(candidate.client).success;
  const deletions = configRebaseDeletionKeys(candidate);
  const explicitClear = deletions.has("client") && deletions.has("runtimeRole");
  if (candidateValid || explicitClear) return null;
  return "config write refused: malformed or mismatched remote client state must be repaired or explicitly cleared";
}

/**
 * Atomic config.json write WITHOUT the mutation lock; callers must hold
 * `withConfigMutationLockSync`. Returns true when bytes changed. Refreshes the
 * cost-overlay registry from the persisted config so runtime estimates follow
 * every save path.
 */
export function persistConfigUnlocked(config: OcxConfig): boolean {
  const pinError = configReasoningPinsConfigError(config);
  if (pinError) throw new Error(pinError);
  const configPath = getConfigPath();
  // Protect late disk edits from these same bytes, retaining raw rows for guards and credential accounting.
  const rawBeforeWrite = readRawConfigJson("preserve-only");
  const clientPersistenceError = failClosedClientPersistenceError(rawBeforeWrite, config);
  if (clientPersistenceError) throw new Error(clientPersistenceError);
  // External editors can add provider rows the live config deliberately does
  // not route with yet; merge them at the serialization boundary so an
  // unrelated in-process save cannot erase the provider or its overlay.
  // Provider preservation reads symbol-keyed live-owner state, which structuredClone
  // intentionally drops. Resolve that ownership before projecting JSON provenance.
  const provenanceProjection = projectConfigRebaseProvenance(config);
  const persisted = withPreservedDiskOnlyProviders(config);
  if (provenanceProjection.configRebaseProvenance === undefined) delete persisted.configRebaseProvenance;
  else persisted.configRebaseProvenance = provenanceProjection.configRebaseProvenance;
  normalizeAccountAutoPauseRevisions(rawBeforeWrite, persisted);
  const beforeFingerprints = snapshotAutoPauseFingerprints(rawBeforeWrite ?? {});
  const bytes = JSON.stringify(persisted, null, 2) + "\n";
  let unchanged = false;
  try {
    unchanged = readFileSync(configPath, "utf8") === bytes;
  } catch (error) {
    if (!isMissingPathError(error)) throw error;
  }
  // Keep the runtime overlay registry in sync with EVERY persist path,
  // including byte-identical saves: a cooperating CLI process may have written
  // the same bytes (e.g. before a proxy notification), and Logs/Usage must
  // adopt the overlay without waiting for a changed save or restart.
  let published = unchanged;
  let observedPublication = false;
  try {
    if (!unchanged) {
      // Register every OS-store reference on either side before a removal can land.
      publishCredentialSync(() => atomicWriteFile(configPath, bytes, undefined, { afterRename: () => { published = true; } }),
        { references: [...new Set([...osStoreAccounts(rawBeforeWrite), ...osStoreAccounts(persisted)])] });
      published = true;
    }
    // Publication, not successful cache refresh, is the rollback boundary. A
    // byte-identical save already has the requested state on disk as well.
    observeAccountAutoPauseRevisions(persisted, persisted, beforeFingerprints);
    observedPublication = true;
    refreshConfigDerivedRegistries(persisted);
    return !unchanged;
  } catch (error) {
    if (published) {
      if (!observedPublication) observeAccountAutoPauseRevisions(persisted, persisted, beforeFingerprints);
      throw new ConfigWritePublishedError(error);
    }
    throw error;
  }
}
