import { observeSignedInCodexIdentity } from "./signed-in-identity";
import { observeMainCodexCollisionIdentity } from "./collision-identity";
import { existsSync, readFileSync } from "node:fs";
import {
  deleteConfigTopLevelKey,
  getConfigPath,
  saveConfigPreservingClaudeCode,
  withConfigMutationLockSync,
} from "../config";
import { captureConfigTopLevelRollback } from "../config/rebase-provenance";
import { removeCodexAccountCredential } from "./account-store";
import { clearAccountNeedsReauth } from "./account-runtime-state";
import { readMainAuth } from "./auth-collision";
import { MAIN_CODEX_ACCOUNT_ID, setMainAccountPlan } from "./main-account";
import { clearAccountQuota, discardMismatchedMainQuota } from "./quota";
import { forgetManualPreference } from "./routing/active-account";
import { deleteAllHealthForAccount } from "./routing/health-store";
import { forgetCodexFailureWindow } from "./routing/failure-window";
import { clearThreadAccountMapForAccount } from "./routing/thread-affinity";

import { clearCodexPoolRefreshFailure } from "./pool-refresh-backoff";
import { invalidateCodexWebSocketsForAccount } from "./websocket-registry";
import { clearMainAccountCredentialPresence, clearMainAccountInfoCache, observeMainQuotaCredential, observeMainQuotaIdentity, type MainQuotaWriter } from "./main-account-cache";
import { extractAccountId, extractAccountIdClaims } from "../oauth/chatgpt";
import { forgetCodexAccountPause } from "./account-pause";
import { forgetCodexAccountCreditUse } from "./account-credit-use";
import { setCodexAccountUseRemainingQuota } from "./account-use-remaining";
import { clearCodexAccountPin, forgetCodexAccountPriority } from "./account-priority";
import { forgetCodexQuotaAutoRefreshAccount } from "./quota-auto-refresh-state";
import { forgetCodexAccountAutoSwitchThreshold } from "./account-auto-switch";
import { codexAccountNamespaceEntries, codexAccountPickerEnabled } from "./account-namespaces";
import type { OcxConfig } from "../types";

let observedMainChatgptAccountId: string | undefined;

export class CodexAccountDeleteCleanupError extends Error {
  constructor() {
    super("Account deletion was saved, but local credential cleanup did not complete. Retry removal.");
    this.name = "CodexAccountDeleteCleanupError";
  }
}

export class CodexAccountDeleteRollbackError extends Error {
  constructor() {
    super("Account deletion failed and the previous config could not be restored. Restart before retrying.");
    this.name = "CodexAccountDeleteRollbackError";
  }
}

export function purgeCodexAccountRuntimeState(accountId: string): void {
  clearAccountNeedsReauth(accountId);
  clearAccountQuota(accountId);
  clearThreadAccountMapForAccount(accountId);
  // Deliberately not via `./routing`: the account-delete path only needs the health rows
  // and their sibling routing state gone, and importing the router barrel here closed a
  // cycle through routing/health-store and routing/active-account. The leaf imports below
  // carry every per-account forget that barrel helper used to perform — including the
  // failure window, whose degrade and pin-warning state must not leak into a replacement
  // account or a new physical login behind __main__.
  deleteAllHealthForAccount(accountId);
  forgetManualPreference(accountId);
  forgetCodexFailureWindow(accountId);
  clearCodexPoolRefreshFailure(accountId);
  if (accountId === MAIN_CODEX_ACCOUNT_ID) {
    clearMainAccountInfoCache();
    clearMainAccountCredentialPresence();
  }
}

function purgeMainCodexAccountRuntimeState(): void {
  purgeCodexAccountRuntimeState(MAIN_CODEX_ACCOUNT_ID);
  setMainAccountPlan(null);
  invalidateCodexWebSocketsForAccount(MAIN_CODEX_ACCOUNT_ID);
}

/** One owned complete identity observation; retire the prior account before publishing the new generation. */
export function observeMainCodexAccountIdentity(accountId: string): boolean {
  if (!accountId) return false;
  const previousAccountId = observedMainChatgptAccountId;
  observedMainChatgptAccountId = accountId;
  const changed = previousAccountId !== undefined && previousAccountId !== accountId;
  if (changed) purgeMainCodexAccountRuntimeState();
  observeMainQuotaIdentity(accountId);
  discardMismatchedMainQuota();
  return changed;
}

/** Only the pinned-home, exclusively claimed Codex RPC may supply this credential. */
export function observeCodexOwnedMainAccountCredential(accessToken: string): MainQuotaWriter | undefined {
  const identity = extractAccountIdClaims(accessToken);
  // An opaque or conflicting answer cannot retire a previously verified identity or its policy.
  if (!identity.accountId || identity.conflict) return undefined;
  observeMainCodexAccountIdentity(identity.accountId);
  const tokens = { access_token: accessToken, account_id: identity.accountId };
  observeSignedInCodexIdentity(tokens);
  observeMainCodexCollisionIdentity(tokens);
  return observeMainQuotaCredential(accessToken, identity.accountId);
}

/**
 * The main Codex login is stored under the stable `__main__` alias, while
 * `~/.codex/auth.json` can be replaced with credentials for another physical
 * ChatGPT account. Drop alias-keyed runtime state when that identity changes so
 * cooldown, quota, reauth, and thread affinity do not leak across accounts.
 */
export function reconcileMainCodexAccountRuntimeState(): boolean {
  const read = readMainAuth();
  if (read.status === "missing" || read.status === "api-key-only") observeMainCodexCollisionIdentity();
  const currentAccountId = read.status === "ok"
    ? extractAccountId(read.tokens.id_token, read.tokens.access_token) ?? (read.tokens.account_id || null)
    : null;
  if (read.status === "ok") observeSignedInCodexIdentity(read.tokens);
  // A missing/malformed auth.json is an unknown identity, not a confirmed account switch. Keep the
  // prior observation and its safety state until a real account id can be read again.
  if (currentAccountId === null) return false;
  const changed = observeMainCodexAccountIdentity(currentAccountId);
  if (read.status === "ok") observeMainCodexCollisionIdentity(read.tokens);
  return changed;
}

/**
 * Rebuild the memory-only policy binding from a startup-owned, recovered auth path.
 * The caller holds the native owner and exclusive claim; an incoming bearer is never evidence.
 * A failed read creates no binding and cannot revoke a prior verified observation or its block.
 * Only a valid replacement observation or confirmed account transition supersedes that evidence.
 */
export function initializeMainAccountPolicyBinding(authPath: string): boolean {
  // Startup observes the pinned owned path inside the exclusive claim: bound the read so a
  // replaced non-regular or oversized file cannot stall startup inside that claim.
  const result = readMainAuth(authPath);
  if (result.status === "missing" || result.status === "api-key-only") observeMainCodexCollisionIdentity();
  if (result.status !== "ok") return false;
  const { tokens } = result;
  if (typeof tokens.access_token !== "string" || !tokens.access_token
    || typeof tokens.account_id !== "string" || !tokens.account_id) return false;
  if (tokens.id_token != null && typeof tokens.id_token !== "string") return false;
  const accountId = tokens.account_id;
  // An owned file may contain an opaque bearer, but every decoded identity must agree —
  // including the two account-id encodings within a single token.
  const idTokenClaims = extractAccountIdClaims(tokens.id_token);
  const accessTokenClaims = extractAccountIdClaims(tokens.access_token);
  if (idTokenClaims.conflict || accessTokenClaims.conflict) return false;
  const idTokenAccountId = idTokenClaims.accountId;
  const accessTokenAccountId = accessTokenClaims.accountId;
  if ((idTokenAccountId !== undefined && idTokenAccountId !== accountId)
    || (accessTokenAccountId !== undefined && accessTokenAccountId !== accountId)) return false;
  const previousAccountId = observedMainChatgptAccountId;
  observedMainChatgptAccountId = accountId;
  if (previousAccountId !== undefined && previousAccountId !== accountId) purgeMainCodexAccountRuntimeState();
  observeSignedInCodexIdentity(tokens);
  observeMainQuotaIdentity(accountId);
  discardMismatchedMainQuota();
  observeMainCodexCollisionIdentity(tokens);
  return observeMainQuotaCredential(tokens.access_token, accountId) !== undefined;
}

/**
 * Apply a transaction-confirmed physical native-login change without waiting for
 * a later auth.json observation. The caller owns credential commit/rollback.
 */
export function applyConfirmedMainCodexAccountTransition(
  fromAccountId: string,
  toAccountId: string,
): boolean {
  observeSignedInCodexIdentity();
  observeMainCodexCollisionIdentity();
  if (!fromAccountId || !toAccountId || fromAccountId === toAccountId) {
    if (toAccountId) {
      observedMainChatgptAccountId = toAccountId;
      observeMainQuotaIdentity(toAccountId);
    }
    return false;
  }
  observedMainChatgptAccountId = toAccountId;
  purgeMainCodexAccountRuntimeState();
  observeMainQuotaIdentity(toAccountId);
  return true;
}

export function resetMainCodexAccountIdentityTrackingForTests(): void {
  observeMainCodexCollisionIdentity();
  observedMainChatgptAccountId = undefined;
  observeSignedInCodexIdentity();
  clearMainAccountCredentialPresence();
}

function restoreRuntimeConfig(target: OcxConfig, snapshot: OcxConfig): void {
  for (const key of Object.keys(target) as Array<keyof OcxConfig>) delete target[key];
  Object.assign(target, snapshot);
}

function assertPersistedConfigUnchanged(configPath: string, previousBytes: Buffer): void {
  if (!readFileSync(configPath).equals(previousBytes)) {
    throw new CodexAccountDeleteRollbackError();
  }
}

/**
 * Delete a stored account while retaining its selector binding.
 *
 * When the runtime config is backed by an existing config.json, commit the config deletion before
 * credentials or runtime state are destroyed. Transient callers intentionally skip durable config
 * persistence because they have no durable account row to protect. The whole sequence shares the
 * config mutation coordinator so a cooperating writer cannot re-add a persisted account between
 * the durable config commit and credential cleanup.
 *
 * Returns true when a picker-visible row disappeared and the catalog must converge.
 */
export function deleteCodexAccount(runtimeConfig: OcxConfig, accountId: string): boolean {
  let cleanupFailed = false;
  const pickerVisibilityChanged = withConfigMutationLockSync(() => {
    const previousConfig = structuredClone(runtimeConfig);
    const restoreDeletionProvenance = captureConfigTopLevelRollback(runtimeConfig, []);
    const configPath = getConfigPath();
    const hasPersistedConfig = existsSync(configPath);
    const previousPersistedConfig = hasPersistedConfig ? readFileSync(configPath) : undefined;
    const hadStoredAccount = (runtimeConfig.codexAccounts ?? [])
      .some(account => !account.isMain && account.id === accountId);
    const hadVisiblePickerBinding = hadStoredAccount
      && codexAccountPickerEnabled(runtimeConfig)
      && codexAccountNamespaceEntries(runtimeConfig)
        .some(([, boundAccountId]) => boundAccountId === accountId);

    runtimeConfig.codexAccounts = (runtimeConfig.codexAccounts ?? [])
      .filter(account => account.isMain || account.id !== accountId);
    forgetCodexAccountPause(runtimeConfig, accountId);
    forgetCodexAccountCreditUse(runtimeConfig, accountId);
    forgetCodexAccountPriority(runtimeConfig, accountId);
    forgetCodexAccountAutoSwitchThreshold(runtimeConfig, accountId);
    setCodexAccountUseRemainingQuota(runtimeConfig, accountId, false);
    if (runtimeConfig.codexQuotaAutoRefresh?.[accountId]) {
      const retained = { ...runtimeConfig.codexQuotaAutoRefresh };
      delete retained[accountId];
      if (Object.keys(retained).length > 0) runtimeConfig.codexQuotaAutoRefresh = retained;
      else deleteConfigTopLevelKey(runtimeConfig, "codexQuotaAutoRefresh");
    }
    clearCodexAccountPin(runtimeConfig, accountId);
    if (runtimeConfig.activeCodexAccountId === accountId) runtimeConfig.activeCodexAccountId = undefined;

    if (previousPersistedConfig !== undefined) {
      try {
        // Persist first for durable configs. Destructive cleanup below must never run for a
        // deletion that failed to commit. Transient configs intentionally skip this write.
        saveConfigPreservingClaudeCode(runtimeConfig);
      } catch (error) {
        restoreRuntimeConfig(runtimeConfig, previousConfig);
        // The value snapshot cannot restore WeakMap-backed deletion intent. Retaining a
        // rejected reset would erase a later disk override when this account inherited.
        restoreDeletionProvenance();
        try {
          assertPersistedConfigUnchanged(configPath, previousPersistedConfig);
        } catch {
          throw new CodexAccountDeleteRollbackError();
        }
        throw error;
      }
    }

    try {
      removeCodexAccountCredential(accountId);
      purgeCodexAccountRuntimeState(accountId);
      invalidateCodexWebSocketsForAccount(accountId);
    } catch {
      // Do not throw through the mutation coordinator after config.json committed: that would roll
      // back only the SQLite generation transaction, not the already-atomic file replacement.
      cleanupFailed = true;
    }

    return hadVisiblePickerBinding;
  });

  forgetCodexQuotaAutoRefreshAccount(accountId);
  if (cleanupFailed) throw new CodexAccountDeleteCleanupError();
  return pickerVisibilityChanged;
}
