import { readClientConnectionState } from "../client/state";
import { readServiceApiTokenState, readTokenBackupState } from "../lib/service-secrets";
import { assertClientLifecycleHeld, withClientLifecycleSync, type ClientLifecycleHeld, type ClientLifecycleLockDeps } from "../client/lifecycle-lock";
import { applyRemoteDesktopStore, inspectRemoteDesktopCleanup, restoreRemoteDesktopStore } from "./desktop-remote-store";
import { canonicalDirectory } from "./desktop-remote-store-io";
import {
  resolveDesktop3pConfigLibraryPath, parseMetadata, SAFE_DESKTOP_PROFILE_ID, isRecord,
  isOwnedDesktopEntry, isOwnedDesktopGatewayEntry, profilePath, readDesktopProfileSnapshot, readDesktopLibraryText, readDesktopLibraryBytes,
  readOptionalDesktopLibraryBytes, assertDesktopLibraryTextSize, serializeDesktopLibraryJson,
  type Desktop3pConfigLibraryOptions, type Desktop3pMetadata, type Desktop3pMetadataEntry,
} from "./desktop-3p-library";
export { resolveDesktop3pConfigLibraryPath, type Desktop3pConfigLibraryOptions } from "./desktop-3p-library";
import { createHash, randomUUID } from "node:crypto";
import { existsSync, mkdirSync, lstatSync, unlinkSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { atomicWriteFile, readConfigDiagnostics, withConfigMutationLockSync } from "../config";
import { atomicWriteFileNoFollow, atomicWriteFileStreamed } from "../config/atomic-write";
import { claudeDesktopIntegrationEnabled } from "../codex/desired-state";
import type { OcxClaudeDesktopProfile } from "../types";
import {
  reconcileDesktopProfile,
  renderDesktopProfile,
  validDateAlias,
  legacyDesktopProfileWireAlias,
  type DesktopProfileModel,
} from "./desktop-profile";
import { nativeOpenAiContextWindow, type NativeContextLimitsInput } from "../codex/catalog";
import { localAdmissionToken, localInferenceDestination } from "../lib/local-destinations";
import { assertDesktop3pModelsValid } from "./desktop-3p-guard";
import { filterDesktopModelsByVisibility, readDesktopModelVisibility, type DesktopModelVisibility } from "./desktop-model-visibility";
import { claudeSurfaceSupportsOneMillion, ONE_MILLION } from "./long-context";

export interface Desktop3pModelEntry {
  name: string;
  labelOverride: string;
  anthropicFamilyTier: "opus" | "fable" | "sonnet" | "haiku";
  isFamilyDefault?: boolean;
  /**
   * Desktop's documented 1M-context capability assertion. Set ONLY from an
   * authoritative routed contextWindow >= 1M — never guessed (devlog 136 B5).
   */
  supports1m?: true;
  /** When true, Desktop selects the 1M variant by default (official schema, Luna research 260722). */
  prefer1m?: true;
}

/**
 * static (default, Pro-verified devlog 138): pinned inferenceModels with
 * modelDiscoveryEnabled:false — a static list OVERRIDES discovery (no merge), so
 * this is the deterministic shape. hybrid keeps discovery:true alongside the list
 * (claude-code-router's version-defensive pattern). discovery: /v1/models only.
 */
export type Desktop3pConfigMode = "hybrid" | "discovery" | "static";

export interface Desktop3pRoutedModel {
  provider: string;
  id: string;
  /** Authoritative context window (CatalogModel.contextWindow); optional. */
  contextWindow?: number;
}

/**
 * The genuine-1M threshold real Anthropic rows still need. Every other row follows the
 * long-window rule; the writer, the profile renderer and the dashboard DTO all decide through
 * `claudeSurfaceSupportsOneMillion` (long-context.ts), so the 1M chip cannot disagree with the
 * written config.
 */
export const DESKTOP_SUPPORTS_1M_THRESHOLD = ONE_MILLION;

/** CLI arg parsing for `ocx claude desktop` mode flags (mutually exclusive). */
export function parseDesktop3pModeArgs(flags: string[]): { mode: Desktop3pConfigMode } | { error: string } {
  const known = new Map<string, Desktop3pConfigMode>([
    ["--static", "static"],
    ["--hybrid", "hybrid"],
    ["--discovery-only", "discovery"],
  ]);
  const unknown = flags.filter(a => !known.has(a));
  if (unknown.length > 0) return { error: `알 수 없는 옵션: ${unknown.join(" ")} (지원: --static, --hybrid, --discovery-only)` };
  const picked = [...new Set(flags.map(a => known.get(a)!))];
  if (picked.length > 1) return { error: "모드 옵션은 하나만 쓸 수 있습니다 (--static | --hybrid | --discovery-only)." };
  return { mode: picked[0] ?? "static" };
}

export type Desktop3pLibraryKind =
  | "not_installed"
  | "standard"
  | "gateway_ours"
  | "gateway_drifted"
  | "foreign"
  | "no_owned_state"
  | "broken"
  | "unsafe";

export interface Desktop3pLibraryInspection {
  kind: Desktop3pLibraryKind;
  libraryPath: string;
  selectedProfilePath: string | null;
  appliedId: string | null;
  /** Paths of opencodex-owned rows that are not selected by Desktop. */
  residualPaths: string[];
  /** Bounded reason code; never includes metadata or profile contents. */
  reason?: "metadata_unreadable" | "unsafe_applied_id" | "invalid_owned_profile";
  fingerprint?: string;
  /**
   * Whether Desktop's applied selection is our owned entry, by ID match alone.
   * `null` = undeterminable (no metadata, unreadable metadata, or no appliedId);
   * a readable appliedId with no owned entry is a KNOWN false, not unknown.
   * Deliberately independent of profile-file health: the status contract
   * predates this inspector and callers render tri-state.
   */
  ownedProfileActive: boolean | null;
}

export interface Desktop3pRemovalResult {
  ok: boolean;
  changed: boolean;
  kind: "removed" | "noop" | "cleanup_incomplete" | "unsafe" | "write_failed";
  libraryPath: string;
  residualPaths?: string[];
  reason?: string;
}

let desktop3pRegistry = new Map<string, string>();
let desktop3pAliasesByRoute = new Map<string, string>();
let desktop3pRealAnthropicIds = new Set<string>();

/** Derive a stable letter-first, three-character base36 code from a route key. */
export function deriveDesktop3pCode(route: string): string {
  const hash = createHash("sha256").update(route).digest();
  const n = hash.readUInt32BE(0) % 33696;
  const first = String.fromCharCode(97 + Math.floor(n / 1296));
  const rest = (n % 1296).toString(36).padStart(2, "0");
  return first + rest;
}

/**
 * Alias for one proxy model. Real Anthropic models pass through unchanged (they must
 * keep hitting the sk-ant native passthrough); everything else gets a Claude-shaped
 * `claude-opus-4-8-{code}` id. Opus 4.8 is chosen deliberately: Desktop's effort
 * selector is an allowlist keyed on exact supported model ids (Opus 4.8/4.7/4.6,
 * Sonnet 4.6 — devlog 131), and 4.6+ canonical ids are dateless, so the letter-first
 * 3-char suffix can never collide with a real id or a legacy date suffix.
 */
export function desktop3pAlias(provider: string, modelId: string): string {
  if (provider === "anthropic" && modelId.startsWith("claude-")) return modelId;
  return `claude-opus-4-8-${deriveDesktop3pCode(`${provider}/${modelId}`)}`;
}

/** Pre-rename alias shape (claude-opus-4-{code}) — still decoded for stale Desktop configs. */
export function legacyDesktop3pAlias(provider: string, modelId: string): string {
  return `claude-opus-4-${deriveDesktop3pCode(`${provider}/${modelId}`)}`;
}

export function displayModelId(modelId: string): string {
  return modelId
    // Capability markers like [1m] are not name text: strip the brackets so the label
    // reads "K3 1M", never "K3[1m]".
    .replace(/\[([^\]]+)\]/g, "-$1")
    .split(/[-_]+/)
    .filter(Boolean)
    .map(part => {
      const lower = part.toLowerCase();
      if (lower === "gpt" || lower === "glm" || lower === "ai" || lower === "1m") return lower.toUpperCase();
      return part.charAt(0).toUpperCase() + part.slice(1);
    })
    .join(" ");
}

function collectDesktop3pModels(
  nativeSlugs: string[],
  routedModels: Array<Desktop3pRoutedModel>,
  profile?: OcxClaudeDesktopProfile,
  nativeContextCap?: NativeContextLimitsInput,
) {
  const registry = new Map<string, string>();
  const aliasesByRoute = new Map<string, string>();
  const models: Desktop3pModelEntry[] = [];
  // routes[i] is the route models[i] serves; visibility filters by route, never by alias.
  const routes: string[] = [];
  const candidates: Desktop3pRoutedModel[] = [
    // Native candidates carry their real context window from the same accessor the
    // Desktop DTO uses, so a native 1M/372k model resolves identically in the written
    // config and on the dashboard.
    ...nativeSlugs.map(id => {
      const contextWindow = nativeOpenAiContextWindow(id, nativeContextCap);
      return { provider: "native", id, ...(contextWindow !== undefined ? { contextWindow } : {}) };
    }),
    ...routedModels,
  ];
  const realAnthropicIds = new Set(candidates
    .filter(model => model.provider === "anthropic" && model.id.startsWith("claude-"))
    .map(model => model.id));

  if (profile) {
    const profileModels = candidates.map(({ provider, id, contextWindow }) => ({
      route: `${provider}/${id}`,
      label: `${displayModelId(id)} (${provider})`,
      ...(typeof contextWindow === "number" ? { contextWindow } : {}),
    } satisfies DesktopProfileModel));
    const reconciled = reconcileDesktopProfile(profile, profileModels);
    const rendered = renderDesktopProfile(reconciled, profileModels);
    for (const model of rendered) {
      const realAnthropic = model.route.startsWith("anthropic/claude-");
      if (!realAnthropic && realAnthropicIds.has(model.name)) {
        console.warn(`[opencodex] Claude Desktop profile alias ${model.name} for ${model.route} conflicts with a real Anthropic model; skipping the routed model`);
        continue;
      }
      aliasesByRoute.set(model.route, model.name);
      if (!realAnthropic) {
        registry.set(model.name, model.route);
        // Profiles persist their historical date slots, while Desktop receives
        // a non-date wire id. Keep the date form resolvable for running/stale
        // sessions during the migration.
        const storedAlias = reconciled.assignments[model.route]?.alias;
        if (storedAlias && storedAlias !== model.name) {
          if (realAnthropicIds.has(storedAlias)) {
            console.warn(`[opencodex] Claude Desktop stored alias ${storedAlias} for ${model.route} conflicts with a real Anthropic model; ignoring the alias`);
          } else {
            registry.set(storedAlias, model.route);
          }
        }
      }
      models.push({
        name: model.name,
        labelOverride: model.label,
        anthropicFamilyTier: model.family,
        ...(model.isFamilyDefault ? { isFamilyDefault: true } : {}),
        ...(model.supports1m ? { supports1m: true, prefer1m: true } : {}),
      });
      routes.push(model.route);
    }
    // Previous profile IDs and both hash generations are compatibility-only and can
    // collide. Bind them in stable route order so changing a family default or
    // rendered ordering can never silently rebind an old Desktop id.
    for (const model of [...rendered].sort((a, b) => a.route.localeCompare(b.route))) {
      if (model.route.startsWith("anthropic/claude-")) continue;
      const providerEnd = model.route.indexOf("/");
      const provider = model.route.slice(0, providerEnd);
      const id = model.route.slice(providerEnd + 1);
      const storedAlias = reconciled.assignments[model.route]!.alias;
      for (const legacy of [legacyDesktopProfileWireAlias(storedAlias), desktop3pAlias(provider, id), legacyDesktop3pAlias(provider, id)]) {
        if (realAnthropicIds.has(legacy)) {
          console.warn(`[opencodex] Claude Desktop legacy alias ${legacy} for ${model.route} conflicts with a real Anthropic model; ignoring the alias`);
          continue;
        }
        const existing = registry.get(legacy);
        if (existing && existing !== model.route) {
          console.warn(`[opencodex] Claude Desktop legacy alias collision: ${legacy} stays bound to ${existing}; ignoring ${model.route}`);
          continue;
        }
        registry.set(legacy, model.route);
      }
    }
    return { models, routes, registry, aliasesByRoute, realAnthropicIds };
  }

  const emittedNames = new Set<string>();
  for (const { provider, id, contextWindow } of candidates) {
    const route = `${provider}/${id}`;
    const alias = desktop3pAlias(provider, id);
    const supports1m = claudeSurfaceSupportsOneMillion(provider, id, contextWindow)
      ? { supports1m: true as const }
      : {};
    if (alias === id) {
      // Real Anthropic model: keep it OUT of the decode registry — registering it would
      // make resolveInboundModel() non-identity and kill the sk-ant native passthrough
      // (audit 133 #1). It still appears in the static Desktop model list below.
      if (emittedNames.has(alias)) continue;
      models.push({
        name: alias,
        labelOverride: `${displayModelId(id)} (${provider})`,
        anthropicFamilyTier: "opus",
        ...supports1m,
        ...(supports1m.supports1m ? { prefer1m: true as const } : {}),
      });
      emittedNames.add(alias);
      routes.push(route);
      aliasesByRoute.set(route, alias);
      continue;
    }
    if (realAnthropicIds.has(alias)) {
      console.warn(`[opencodex] Claude Desktop 3P alias ${alias} for ${route} conflicts with a real Anthropic model; skipping the routed model`);
      continue;
    }
    const existingRoute = registry.get(alias);
    if (existingRoute !== undefined) {
      console.warn(`[opencodex] Claude Desktop 3P alias collision: ${alias} maps to both ${existingRoute} and ${route}; skipping ${route}`);
      continue;
    }

    registry.set(alias, route);
    // Back-compat decode for Desktop configs written before the opus-4-8 rename.
    const legacy = legacyDesktop3pAlias(provider, id);
    if (realAnthropicIds.has(legacy)) {
      console.warn(`[opencodex] Claude Desktop legacy alias ${legacy} for ${route} conflicts with a real Anthropic model; ignoring the alias`);
    } else if (!registry.has(legacy)) {
      registry.set(legacy, route);
    }
    models.push({
      name: alias,
      labelOverride: `${displayModelId(id)} (${provider})`,
      anthropicFamilyTier: "opus",
      ...supports1m,
      ...(supports1m.supports1m ? { prefer1m: true as const } : {}),
    });
    routes.push(route);
    aliasesByRoute.set(route, alias);
  }

  if (models[0]) models[0].isFamilyDefault = true;
  return { models, routes, registry, aliasesByRoute, realAnthropicIds };
}

function installDesktop3pRegistry({ registry, aliasesByRoute, realAnthropicIds }: ReturnType<typeof collectDesktop3pModels>): void {
  desktop3pRegistry = registry;
  desktop3pAliasesByRoute = aliasesByRoute;
  desktop3pRealAnthropicIds = realAnthropicIds;
}

/** Build and install the registry used to decode Desktop aliases. */
export function buildDesktop3pRegistry(
  nativeSlugs: string[],
  routedModels: Array<Desktop3pRoutedModel>,
  profile?: OcxClaudeDesktopProfile,
  nativeContextCap?: NativeContextLimitsInput,
): Map<string, string> {
  const collected = collectDesktop3pModels(nativeSlugs, routedModels, profile, nativeContextCap);
  installDesktop3pRegistry(collected);
  return collected.registry;
}

/** Generate Claude Desktop 3P model entries from the proxy's available models. */
export interface Desktop3pModelOptions {
  /**
   * false under claudeCode.contextAccounting "200k": a long-window model stays selectable at 1M
   * (`supports1m`) but no longer defaults to it (`prefer1m` dropped).
   */
  preferOneMillion?: boolean;
  /**
   * Rows Desktop lists (#7702). Filters only the emitted list: the decode registry keeps every
   * route so a running session holding a just-hidden alias still routes.
   */
  visibility?: DesktopModelVisibility;
}

export function generateDesktop3pModels(
  nativeSlugs: string[],
  routedModels: Array<Desktop3pRoutedModel>,
  profile?: OcxClaudeDesktopProfile,
  nativeContextCap?: NativeContextLimitsInput,
  options: Desktop3pModelOptions = {},
): Desktop3pModelEntry[] {
  const collected = collectDesktop3pModels(nativeSlugs, routedModels, profile, nativeContextCap);
  installDesktop3pRegistry(collected);
  const { models: all, routes } = collected;
  let models = filterDesktopModelsByVisibility(all, routes, options.visibility);
  if (models.length === 0 && all.length > 0) {
    // An empty static list leaves Desktop with no usable picker. The dashboard refuses to save
    // such a selection; this covers selections whose every model has since disappeared.
    console.warn("[opencodex] Claude Desktop model visibility hides every available model; listing all models instead");
    models = all;
  }
  return options.preferOneMillion === false ? models.map(({ prefer1m: _prefer1m, ...model }) => model) : models;
}

/** The Desktop model options a config asks for (one place, so writer and export agree). */
export function desktop3pModelOptions(
  claudeCode: { contextAccounting?: string; desktopModelVisibility?: unknown } | undefined,
): Desktop3pModelOptions {
  const visibility = readDesktopModelVisibility(claudeCode);
  return { preferOneMillion: claudeCode?.contextAccounting !== "200k", ...(visibility ? { visibility } : {}) };
}

/** Resolve an alias using the most recently generated Desktop model registry. */
export function resolveDesktop3pAlias(alias: string): string | null {
  return desktop3pRegistry.get(alias) ?? null;
}

/** Number of decodable aliases in the installed registry (0 before the first build). */
export function desktop3pRegistrySize(): number {
  return desktop3pRegistry.size;
}

/** Exact registered and identity-preserving catalog IDs precede synthetic syntax. */
export function isKnownDesktop3pModelId(id: string): boolean {
  return desktop3pRegistry.has(id) || desktop3pRealAnthropicIds.has(id);
}

/** Real catalog IDs retain identity even when their spelling resembles an alias. */
export function isRealDesktop3pModelId(id: string): boolean {
  return desktop3pRealAnthropicIds.has(id);
}

/** Only missing IDs in the emitted Desktop namespaces are managed-alias errors. */
export function isUnresolvedDesktop3pAlias(id: string): boolean {
  if (isKnownDesktop3pModelId(id)) return false;
  // Validate the managed base even when Fast routing is disabled. This checks
  // identity only; it neither enables a tier nor strips an exact full catalog ID.
  const base = id.endsWith("--fast") ? id.slice(0, -"--fast".length) : id;
  if (isKnownDesktop3pModelId(base)) return false;
  return validDateAlias(base)
    || /^claude-opus-4-(?:8-)?[a-z][a-z0-9]{2}$/.test(base)
    || /^claude-(?:opus-4-8|fable-5)-p[0-9a-z]{3}$/.test(base);
}

/** Alias selected by the installed profile registry, falling back to the legacy hash shape. */
export function activeDesktop3pAlias(provider: string, modelId: string): string {
  return desktop3pAliasesByRoute.get(`${provider}/${modelId}`) ?? desktop3pAlias(provider, modelId);
}

/** Discovery cannot offer a skipped alias or one owned by a different route. */
export function resolvableDesktop3pAlias(provider: string, modelId: string): string | undefined {
  if (provider === "anthropic" && modelId.startsWith("claude-")) {
    return desktop3pRealAnthropicIds.has(modelId) ? modelId : undefined;
  }
  const alias = activeDesktop3pAlias(provider, modelId);
  return resolveDesktop3pAlias(alias) === `${provider}/${modelId}` ? alias : undefined;
}

/**
 * Generate the complete Claude Desktop 3P gateway config.
 *
 * Default mode is "static" (Pro-verified, devlog 138): the static list is the ONLY
 * channel for supports1m/tier pins and it overrides discovery anyway (no merge), so
 * discovery stays off for determinism. supports1m makes Desktop offer a separate 1M
 * row; selecting it sends the bare id + `anthropic-beta: context-1m-2025-08-07`.
 *
 * `portOrOrigin` is the LOCAL destination Desktop should dial, already resolved by the caller
 * (see `writeDesktop3pConfig`): on a hub that is the unauthenticated loopback listener, and with
 * no listener the bind address — which is why an ORIGIN is accepted and not only a port. A bare
 * port keeps meaning `http://127.0.0.1:<port>`, so every existing caller and test is unchanged.
 */
export function generateDesktop3pConfig(
  portOrOrigin: number | string,
  nativeSlugs: string[],
  routedModels: Array<Desktop3pRoutedModel>,
  apiKey = "ocx",
  mode: Desktop3pConfigMode = "static",
  profile?: OcxClaudeDesktopProfile,
  nativeContextCap?: NativeContextLimitsInput,
  options: Desktop3pModelOptions = {},
): object {
  const base = {
    inferenceProvider: "gateway",
    inferenceCredentialKind: "static",
    inferenceGatewayBaseUrl: typeof portOrOrigin === "number" ? `http://127.0.0.1:${portOrOrigin}` : portOrOrigin,
    inferenceGatewayApiKey: apiKey,
  };
  if (mode === "discovery") {
    // Build/refresh the decode registry even though no static list is emitted.
    buildDesktop3pRegistry(nativeSlugs, routedModels, profile, nativeContextCap);
    return { ...base, modelDiscoveryEnabled: true };
  }
  return {
    ...base,
    modelDiscoveryEnabled: mode === "hybrid",
    inferenceModels: (() => {
      const models = generateDesktop3pModels(nativeSlugs, routedModels, profile, nativeContextCap, options);
      // Fail loud at the write boundary rather than ship a config Desktop rejects:
      // the output counterpart of the request-path guards.
      assertDesktop3pModelsValid(models);
      return models;
    })(),
  };
}

/**
 * Read Desktop's selected config without changing its library.
 *
 * This is intentionally separate from the eager writer below: status probes must
 * never manufacture a config-library directory on a machine without Desktop.
 */
export function inspectDesktop3pConfigLibrary(
  options: Desktop3pConfigLibraryOptions & { appliedFingerprint?: string | null } = {},
): Desktop3pLibraryInspection {
  const libraryPath = resolveDesktop3pConfigLibraryPath(options);
  if (!existsSync(libraryPath)) {
    return { kind: "not_installed", libraryPath, selectedProfilePath: null, appliedId: null, residualPaths: [], ownedProfileActive: null };
  }

  const metadataPath = join(libraryPath, "_meta.json");
  if (!existsSync(metadataPath)) {
    return { kind: "no_owned_state", libraryPath, selectedProfilePath: null, appliedId: null, residualPaths: [], ownedProfileActive: null };
  }

  let metadata: Desktop3pMetadata;
  try {
    metadata = parseMetadata(metadataPath);
  } catch {
    return {
      kind: "unsafe", libraryPath, selectedProfilePath: null, appliedId: null, residualPaths: [], reason: "metadata_unreadable", ownedProfileActive: null,
    };
  }
  const appliedId = typeof metadata.appliedId === "string" ? metadata.appliedId : null;
  if (appliedId === null) {
    return { kind: "no_owned_state", libraryPath, selectedProfilePath: null, appliedId: null, residualPaths: [], ownedProfileActive: null };
  }
  const selected = metadata.entries.find(entry => entry?.id === appliedId);
  // A readable appliedId with no owned entry is a KNOWN false, not unknown.
  const ownedProfileActive = isOwnedDesktopEntry(selected);
  if (!SAFE_DESKTOP_PROFILE_ID.test(appliedId)) {
    return {
      kind: "unsafe", libraryPath, selectedProfilePath: null, appliedId, residualPaths: [], reason: "unsafe_applied_id", ownedProfileActive,
    };
  }

  const selectedProfilePath = profilePath(libraryPath, appliedId);
  const residualPaths = metadata.entries
    .filter(entry => isOwnedDesktopGatewayEntry(entry) && entry.id !== appliedId && SAFE_DESKTOP_PROFILE_ID.test(entry.id))
    .flatMap(entry => [profilePath(libraryPath, entry.id), `${profilePath(libraryPath, entry.id)}.bak`])
    .filter(existsSync);
  if (!existsSync(selectedProfilePath)) {
    return { kind: "broken", libraryPath, selectedProfilePath, appliedId, residualPaths, ownedProfileActive };
  }

  let profile: Record<string, unknown>;
  let fingerprint: string;
  try {
    const source = readDesktopLibraryText(selectedProfilePath);
    const parsed = JSON.parse(source) as unknown;
    if (!isRecord(parsed)) return { kind: "broken", libraryPath, selectedProfilePath, appliedId, residualPaths, ownedProfileActive };
    profile = parsed;
    fingerprint = createHash("sha256").update(source).digest("hex").slice(0, 16);
  } catch {
    return { kind: "broken", libraryPath, selectedProfilePath, appliedId, residualPaths, ownedProfileActive };
  }
  if (!isOwnedDesktopEntry(selected)) {
    return { kind: "foreign", libraryPath, selectedProfilePath, appliedId, residualPaths, fingerprint, ownedProfileActive };
  }
  if (profile.inferenceProvider === undefined) {
    return { kind: "standard", libraryPath, selectedProfilePath, appliedId, residualPaths, fingerprint, ownedProfileActive };
  }
  const validGateway = profile.inferenceProvider === "gateway"
    && profile.inferenceCredentialKind === "static"
    && typeof profile.inferenceGatewayBaseUrl === "string"
    && typeof profile.inferenceGatewayApiKey === "string";
  if (!validGateway) {
    return {
      kind: "unsafe", libraryPath, selectedProfilePath, appliedId, residualPaths, fingerprint, reason: "invalid_owned_profile", ownedProfileActive,
    };
  }
  return {
    kind: options.appliedFingerprint && options.appliedFingerprint === fingerprint ? "gateway_ours" : "gateway_drifted",
    libraryPath, selectedProfilePath, appliedId, residualPaths, fingerprint, ownedProfileActive,
  };
}

/**
 * Select a credential-free standard profile before deleting an owned gateway.
 * The old metadata row remains as a retry locator only until both its profile
 * and backup are absent; successful cleanup removes it in the same operation.
 *
 * `gateway_drifted` is still an owned opencodex gateway (name + valid shape); the
 * fingerprint only says on-disk bytes differ from the last saved marker. Refusing
 * OFF for drift left users unable to disable after a lost `appliedFingerprint`
 * (or any other benign mismatch), while the Integrations card still showed the
 * leftover profile as applied/stale.
 */
/** Keep failures diagnosable without reflecting paths, config bytes or arbitrary errors. */
function desktopMutationFailureReason(error: unknown): string {
  const code = error !== null && typeof error === "object" && "code" in error ? error.code : undefined;
  switch (code) {
    case "client_lifecycle_busy": return "client_lifecycle_busy";
    case "client_lifecycle_lock_failed": return "client_lifecycle_lock_failed";
    case "CONFIG_MUTATION_LOCK_UNAVAILABLE": return "config_mutation_lock_unavailable";
    case "EACCES":
    case "EPERM": return "desktop_filesystem_denied";
    case "ENOENT": return "desktop_path_missing";
    case "EBUSY": return "desktop_filesystem_busy";
    default: return "desktop_mutation_failed";
  }
}

export function removeDesktop3pStandardPivot(
  options: Desktop3pConfigLibraryOptions & {
    appliedFingerprint?: string | null; unlink?: (path: string) => void;
    lifecycleLockDeps?: ClientLifecycleLockDeps;
    lifecycleHeld?: ClientLifecycleHeld;
    /**
     * The desired-state guard below exists for OFF flows racing a concurrent enable. A
     * mode switch (gateway → first-party) removes the profile while the integration stays
     * ON on purpose, so the caller opts out of that guard.
     */
    replaceWhileEnabled?: boolean;
  } = {},
): Desktop3pRemovalResult {
  const libraryPath = resolveDesktop3pConfigLibraryPath(options);
  try {
    const remove = (held: ClientLifecycleHeld): Desktop3pRemovalResult => withConfigMutationLockSync(() => {
      const connection = readClientConnectionState();
      if (connection.kind === "invalid" || connection.kind === "mismatched") {
        return { ok: false, changed: false, kind: "unsafe", libraryPath, reason: `desktop_client_state_${connection.kind}` };
      }
      if (connection.kind === "connected"
        && canonicalDirectory(libraryPath) !== canonicalDirectory(resolveDesktop3pConfigLibraryPath())) {
        return { ok: false, changed: false, kind: "unsafe", libraryPath, reason: "desktop_library_identity_changed" };
      }
      const latest = readConfigDiagnostics();
      if (latest.source === "fallback") return { ok: false, changed: false, kind: "unsafe", libraryPath, reason: "desktop_config_invalid" };
      if (!options.replaceWhileEnabled && claudeDesktopIntegrationEnabled(latest.config)) {
        const observed = inspectDesktop3pConfigLibrary(options);
        if (observed.kind === "not_installed" || observed.kind === "no_owned_state") {
          return { ok: true, changed: false, kind: "noop", libraryPath };
        }
        return { ok: false, changed: false, kind: "unsafe", libraryPath, reason: "desired_state_changed" };
      }
      const cleanup = inspectRemoteDesktopCleanup();
      if (cleanup.kind === "absent") {
        if (connection.kind === "disconnected") return removeDesktop3pStandardPivotLocal(options);
        const client = connection.value;
        const known = [readServiceApiTokenState(), readTokenBackupState()].flatMap(token => token.kind === "present" ? [token.fingerprint] : []);
        const result = restoreRemoteDesktopStore(held, {
          owner: { serverUrl: new URL(client.serverUrl).origin, apiKeyId: client.apiKeyId, connectedAt: client.connectedAt },
          knownTokenFingerprints: known,
        });
        return result.ok
          ? { ok: true, changed: result.changed, kind: result.changed ? "removed" : "noop", libraryPath }
          : { ok: false, changed: result.changed, kind: "unsafe", reason: result.reason, libraryPath };
      }
      if (cleanup.kind === "unsafe" || canonicalDirectory(libraryPath) !== canonicalDirectory(resolveDesktop3pConfigLibraryPath())) {
        return { ok: false, changed: false, kind: "unsafe", libraryPath };
      }
      const known = [readServiceApiTokenState(), readTokenBackupState()]
        .flatMap(token => token.kind === "present" ? [token.fingerprint] : []);
      const result = restoreRemoteDesktopStore(held, { owner: cleanup.owner, knownTokenFingerprints: known });
      return result.ok
        ? { ok: true, changed: result.changed, kind: result.changed ? "removed" : "noop", libraryPath }
        : { ok: false, changed: result.changed, kind: result.reason === "cleanup_pending" ? "cleanup_incomplete" : "unsafe", reason: result.reason, libraryPath };
    });
    if (options.lifecycleHeld) { assertClientLifecycleHeld(options.lifecycleHeld); return remove(options.lifecycleHeld); }
    return withClientLifecycleSync(remove, options.lifecycleLockDeps);
  } catch (error) {
    return { ok: false, changed: false, kind: "write_failed", libraryPath, reason: desktopMutationFailureReason(error) };
  }
}

function removeDesktop3pStandardPivotLocal(
  options: Desktop3pConfigLibraryOptions & {
    appliedFingerprint?: string | null;
    unlink?: (path: string) => void;
  } = {},
): Desktop3pRemovalResult {
  const inspected = inspectDesktop3pConfigLibrary(options);
  if (inspected.kind === "not_installed" || inspected.kind === "no_owned_state") {
    return { ok: true, changed: false, kind: "noop", libraryPath: inspected.libraryPath };
  }
  if (inspected.kind === "broken" || inspected.kind === "unsafe") {
    return { ok: false, changed: false, kind: "unsafe", libraryPath: inspected.libraryPath, reason: inspected.reason };
  }
  if (!inspected.appliedId || !SAFE_DESKTOP_PROFILE_ID.test(inspected.appliedId)) {
    return { ok: false, changed: false, kind: "unsafe", libraryPath: inspected.libraryPath, reason: "unsafe_applied_id" };
  }

  const metadataPath = join(inspected.libraryPath, "_meta.json");
  try {
    const metadata = parseMetadata(metadataPath);
    const selectedId = inspected.appliedId;
    // When Desktop is actively using our gateway (current or drifted), pivot only
    // that selected row first. Any second owned row is residue for a later
    // standard-mode retry; this preserves the selected-row preference after an
    // interrupted cleanup.
    const selectedOwnedGatewayActive =
      inspected.kind === "gateway_ours" || inspected.kind === "gateway_drifted";
    const targetIds = selectedOwnedGatewayActive
      ? [selectedId]
      : metadata.entries
        .filter(isOwnedDesktopGatewayEntry)
        .map(entry => entry.id)
        .filter(id => SAFE_DESKTOP_PROFILE_ID.test(id));
    if (targetIds.length === 0) return { ok: true, changed: false, kind: "noop", libraryPath: inspected.libraryPath };

    let metadataAfterPivot = metadata;
    let standardPath: string | undefined;
    let pivotMetadataJson: string | undefined;
    if (selectedOwnedGatewayActive) {
      const standardId = randomUUID();
      standardPath = profilePath(inspected.libraryPath, standardId);
      const standardEntry: Desktop3pMetadataEntry = { id: standardId, name: "opencodex-standard" };
      metadataAfterPivot = { ...metadata, appliedId: standardId, entries: [...metadata.entries, standardEntry] };
      pivotMetadataJson = serializeDesktopLibraryJson(metadataAfterPivot);
    }
    // Bound the final metadata before any unlink so a size refusal cannot strand
    // a row pointing at an already-deleted profile.
    const removalMetadataJson = serializeDesktopLibraryJson({
      ...metadataAfterPivot,
      entries: metadataAfterPivot.entries.filter(entry => !targetIds.includes(entry.id)),
    });
    if (standardPath !== undefined && pivotMetadataJson !== undefined) {
      atomicWriteFile(standardPath, "{}\n");
      atomicWriteFile(metadataPath, pivotMetadataJson);
    }

    const residualPaths: string[] = [];
    for (const id of targetIds) {
      for (const candidate of [profilePath(inspected.libraryPath, id), `${profilePath(inspected.libraryPath, id)}.bak`]) {
        try {
          if (existsSync(candidate)) (options.unlink ?? unlinkSync)(candidate);
        } catch {
          // Only the path is allowed to leave this credential-bearing cleanup boundary.
        }
        if (existsSync(candidate)) residualPaths.push(candidate);
      }
    }
    const ownedResiduePaths = metadataAfterPivot.entries
      .filter(entry => isOwnedDesktopGatewayEntry(entry) && !targetIds.includes(entry.id) && SAFE_DESKTOP_PROFILE_ID.test(entry.id))
      .flatMap(entry => [profilePath(inspected.libraryPath, entry.id), `${profilePath(inspected.libraryPath, entry.id)}.bak`])
      .filter(existsSync);
    if (residualPaths.length > 0 || ownedResiduePaths.length > 0) {
      return {
        ok: false, changed: true, kind: "cleanup_incomplete", libraryPath: inspected.libraryPath,
        residualPaths: [...new Set([...residualPaths, ...ownedResiduePaths])],
      };
    }
    // Do not leave a metadata row pointing at a deleted profile. For a foreign
    // selection this only removes proven opencodex residues; appliedId is kept.
    atomicWriteFile(metadataPath, removalMetadataJson);
    return { ok: true, changed: true, kind: "removed", libraryPath: inspected.libraryPath };
  } catch (error) {
    return { ok: false, changed: false, kind: "write_failed", libraryPath: inspected.libraryPath, reason: desktopMutationFailureReason(error) };
  }
}

/** Write and apply the opencodex config in Claude Desktop 3P's config library. */
export function writeDesktop3pConfig(
  port: number,
  nativeSlugs: string[],
  routedModels: Array<Desktop3pRoutedModel>,
  apiKey?: string,
  mode: Desktop3pConfigMode = "static",
  profile?: OcxClaudeDesktopProfile,
  nativeContextCap?: NativeContextLimitsInput,
  lifecycleLockDeps?: ClientLifecycleLockDeps,
  refreshOnly?: { appliedFingerprint: string; admit: () => boolean },
  lifecycleHeld?: ClientLifecycleHeld,
): { written: boolean; path: string; reason?: string; fingerprint?: string } {
  try {
    const write = () => withConfigMutationLockSync(() => {
      const connection = readClientConnectionState();
      if (connection.kind === "invalid" || connection.kind === "mismatched") {
        return { written: false, path: resolveDesktop3pConfigLibraryPath(), reason: `desktop_client_state_${connection.kind}` };
      }
      const latest = readConfigDiagnostics();
      if (latest.source === "fallback") return { written: false, path: resolveDesktop3pConfigLibraryPath(), reason: "desktop_config_invalid" };
      if (!claudeDesktopIntegrationEnabled(latest.config)) {
        return { written: false, path: resolveDesktop3pConfigLibraryPath(), reason: "desired_state_changed" };
      }
      if (refreshOnly && !desktopRefreshPathsSafe(resolveDesktop3pConfigLibraryPath())) {
        return { written: false, path: resolveDesktop3pConfigLibraryPath(), reason: "desktop_refresh_only_skipped" };
      }
      if (connection.kind === "connected" || inspectRemoteDesktopCleanup().kind !== "absent") {
        return { written: false, path: resolveDesktop3pConfigLibraryPath(), reason: "desktop_remote_store_active" };
      }
      let requiredId: string | undefined;
      if (refreshOnly) {
        const refused = { written: false, path: resolveDesktop3pConfigLibraryPath(), reason: "desktop_refresh_only_skipped" };
        // Ownership and bytes must still match under L→C; discovery outside these locks is not authority.
        if (!refreshOnly.admit() || latest.config.claudeCode?.desktopProfile?.appliedFingerprint !== refreshOnly.appliedFingerprint) return refused;
        const inspected = inspectDesktop3pConfigLibrary({ appliedFingerprint: refreshOnly.appliedFingerprint });
        if (inspected.kind !== "gateway_ours" || !inspected.appliedId || !inspected.selectedProfilePath) return refused;
        if (!desktopRefreshPathsSafe(inspected.libraryPath, inspected.selectedProfilePath)) return refused;
        const metadata = parseMetadata(join(inspected.libraryPath, "_meta.json"));
        if (!isOwnedDesktopGatewayEntry(metadata.entries.find(entry => entry.id === inspected.appliedId))) return refused;
        try {
          const selected = JSON.parse(readDesktopLibraryText(inspected.selectedProfilePath)) as Record<string, unknown>;
          mode = selected.modelDiscoveryEnabled !== true ? "static"
            : Array.isArray(selected.inferenceModels) ? "hybrid" : "discovery";
        } catch { return refused; }
        requiredId = inspected.appliedId;
      }
      // Claude Desktop runs on this machine, so it dials the unauthenticated loopback listener
      // when one is enabled — on such a hub that is the only credential-free local socket
      // (#4236) — and otherwise the bind address, which answers but demands data-plane
      // admission. Resolved here, from the config this write already re-read, rather than in
      // the pure generator: `latest.config` is the freshest answer any caller could pass in.
      const destination = localInferenceDestination(latest.config, port);
      // Desktop can carry a credential, so it does: the key the caller passed (the first
      // configured `apiKeys` entry), else the env token / hardened service token file. This is
      // the DATA-PLANE secret only — an admin token must never enter an exported client
      // configuration (reviewer constraint on #4236).
      const gatewayKey = destination.requiresAdmissionToken
        ? apiKey ?? localAdmissionToken(latest.config)
        : apiKey;
      if (destination.requiresAdmissionToken && !gatewayKey) {
        // The placeholder the generator defaults to would 401 on this bind. Write the profile
        // anyway — a reachable URL with a visible auth failure beats a dead socket — but say so.
        console.error(
          `⚠ Claude Desktop will dial ${destination.origin}, which requires an opencodex data-plane `
          + "credential that could not be resolved. Configure an API key or enable "
          + "`unauthenticatedLoopbackListener`.",
        );
      }
      return writeDesktop3pConfigWithGenerator(() => (
        generateDesktop3pConfig(destination.origin, nativeSlugs, routedModels, gatewayKey, mode, profile, nativeContextCap,
          desktop3pModelOptions(latest.config.claudeCode))
      ), requiredId && refreshOnly ? { requiredId, expectedFingerprint: refreshOnly.appliedFingerprint, admit: refreshOnly.admit } : undefined);
    });
    if (lifecycleHeld) { assertClientLifecycleHeld(lifecycleHeld); return write(); }
    return withClientLifecycleSync(write, lifecycleLockDeps);
  } catch { return { written: false, path: resolveDesktop3pConfigLibraryPath(), reason: "desktop_lifecycle_busy_or_unsafe" }; }
}

/** Write the hub's exact entries without constructing a client-local alias registry. */
export function writeRemoteDesktop3pConfig(options: {
  baseUrl: string;
  apiKey: string;
  mode: Desktop3pConfigMode;
  models: Desktop3pModelEntry[];
  lifecycleLockDeps?: ClientLifecycleLockDeps;
}): { written: boolean; path: string; reason?: string; fingerprint?: string } {
  try {
    return withClientLifecycleSync(held => {
      const connection = readClientConnectionState();
      const token = readServiceApiTokenState();
      if (connection.kind !== "connected" || token.kind !== "present") {
        return { written: false, path: "", reason: "desktop_remote_connection_required" };
      }
      const client = connection.value;
      const result = applyRemoteDesktopStore(held, {
        baseUrl: options.baseUrl, apiKey: options.apiKey, mode: options.mode, models: options.models,
        owner: { serverUrl: new URL(client.serverUrl).origin, apiKeyId: client.apiKeyId, connectedAt: client.connectedAt },
        expectedTokenFingerprint: token.fingerprint,
      });
      return result.ok
        ? { written: result.status === "applied", path: result.path ?? "", fingerprint: result.fingerprint }
        : { written: false, path: "", reason: result.reason };
    }, options.lifecycleLockDeps);
  } catch { return { written: false, path: "", reason: "desktop_lifecycle_busy_or_unsafe" }; }
}

/** Refresh-only writes never follow links, including a dangling backup link. */
function desktopRefreshPathsSafe(libraryPath: string, configPath?: string): boolean {
  try {
    if (!lstatSync(libraryPath).isDirectory() || !lstatSync(join(libraryPath, "_meta.json")).isFile()) return false;
    if (configPath) {
      if (!lstatSync(configPath).isFile()) return false;
      try { if (lstatSync(`${configPath}.bak`).isSymbolicLink()) return false; }
      catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") return false; }
    }
    return true;
  } catch { return false; }
}

/** Publish a gateway profile from a verified snapshot, rolling it back if metadata fails. */
function writeDesktop3pConfigWithGenerator(
  generate: () => object,
  refreshOnly?: { requiredId: string; expectedFingerprint: string; admit: () => boolean },
): { written: boolean; path: string; reason?: string; fingerprint?: string } {
  const libraryPath = resolveDesktop3pConfigLibraryPath();
  const metadataPath = join(libraryPath, "_meta.json");
  let configPath = libraryPath;

  try {
    if (refreshOnly && !desktopRefreshPathsSafe(libraryPath)) {
      return { written: false, path: libraryPath, reason: "desktop_refresh_only_skipped" };
    }
    if (!refreshOnly) mkdirSync(libraryPath, { recursive: true, mode: 0o700 });
    const metadata = parseMetadata(metadataPath);
    const selected = metadata.entries.find(entry => entry?.id === metadata.appliedId && isOwnedDesktopGatewayEntry(entry));
    // A refresh may reuse only the applied entry; fallback allocation would silently enroll again.
    if (refreshOnly && selected?.id !== refreshOnly.requiredId) {
      return { written: false, path: libraryPath, reason: "desktop_refresh_only_skipped" };
    }
    const existing = selected ?? metadata.entries.find(entry => isOwnedDesktopGatewayEntry(entry) && typeof entry.id === "string");
    const id = existing?.id ?? randomUUID();
    configPath = profilePath(libraryPath, id);
    const entry: Desktop3pMetadataEntry = existing ? { ...existing, id, name: "opencodex" } : { id, name: "opencodex" };
    const entries = existing
      ? metadata.entries.map(current => current === existing ? entry : current)
      : [...metadata.entries, entry];

    const generated = generate();
    const previous = readDesktopProfileSnapshot(configPath);
    const configJson = serializeDesktopLibraryJson({ ...previous.foreign, ...generated });
    const fingerprint = createHash("sha256").update(configJson).digest("hex").slice(0, 16);
    if (refreshOnly) {
      atomicWriteFileNoFollow(configPath, configJson, undefined, {
        validateBeforeRename: () => {
          try {
            if (!refreshOnly.admit() || !desktopRefreshPathsSafe(libraryPath, configPath)) throw new Error();
            const freshMetadata = parseMetadata(metadataPath);
            if (freshMetadata.appliedId !== refreshOnly.requiredId
              || !isOwnedDesktopGatewayEntry(freshMetadata.entries.find(entry => entry.id === refreshOnly.requiredId))
              || createHash("sha256").update(readDesktopLibraryBytes(configPath)).digest("hex").slice(0, 16) !== refreshOnly.expectedFingerprint) {
              throw new Error();
            }
          } catch { throw new Error("desktop_refresh_only_skipped"); }
        },
      });
      return { written: true, path: configPath, fingerprint };
    }
    const metadataJson = serializeDesktopLibraryJson({ ...metadata, appliedId: id, entries });
    atomicReplaceDesktopConfig(configPath, configJson, previous.bytes);
    try {
      atomicWriteFile(metadataPath, metadataJson);
    } catch (metaError) {
      // Roll back from the verified bytes in memory: reopening the backup could meet a swapped
      // entry and leave the new profile beside the old metadata. A profile this call created is
      // unreferenced once metadata failed, so remove it rather than orphan one per retry.
      // Rollback is ownership-aware: it acts only while the live profile still holds the bytes
      // this call published, checked by the same comparison that guarded publication.
      const base = metaError instanceof Error ? metaError.message : String(metaError);
      const published = Buffer.from(configJson);
      let owned = false;
      const stillOwned = () => { owned = false; assertDesktopProfileUnchanged(configPath, published); owned = true; };
      try {
        stillOwned();
        if (previous.bytes !== undefined) writeDesktopConfigBytes(configPath, previous.bytes, stillOwned);
        else unlinkSync(configPath);
      } catch (rollbackError) {
        if (!owned) {
          // Another writer replaced the profile after publication; its bytes win over our rollback.
          throw new Error(`${base} (profile rollback skipped: profile changed after publish)`, { cause: metaError });
        }
        const detail = rollbackError instanceof Error ? rollbackError.message : String(rollbackError);
        throw new AggregateError([metaError, rollbackError], `${base} (profile rollback also failed: ${detail})`, { cause: metaError });
      }
      throw metaError;
    }
    return { written: true, path: configPath, fingerprint };
  } catch (error) {
    const reason = error instanceof Error ? error.message : String(error);
    return { written: false, path: configPath, reason };
  }
}

/**
 * Compare the live profile with the caller's verified bytes before backup and before replacement.
 * Refuse drift without retrying; backup and rollback continue to use the original verified bytes.
 * `previous` is undefined only for an absent profile, which leaves any older backup alone.
 * Exported for failure-path tests.
 */
export function atomicReplaceDesktopConfig(
  path: string,
  content: string,
  previous: Buffer | undefined,
  writer: typeof atomicWriteFileNoFollow = atomicWriteFileNoFollow,
): { backupPath?: string } {
  assertDesktopLibraryTextSize(content);
  const validateBeforeRename = () => assertDesktopProfileUnchanged(path, previous);
  validateBeforeRename();
  const backupPath = `${path}.bak`;
  if (previous !== undefined) writeDesktopConfigBytes(backupPath, previous);
  writer(path, content, undefined, { validateBeforeRename });
  return previous === undefined ? {} : { backupPath };
}

/** Single compare-and-swap check: the live profile must still hold `expected` (undefined = absent). */
function assertDesktopProfileUnchanged(path: string, expected: Buffer | undefined): void {
  const current = readOptionalDesktopLibraryBytes(path);
  if (expected === undefined ? current !== undefined : current === undefined || !expected.equals(current)) {
    throw new Error("desktop_profile_changed");
  }
}

/** Publish the verified bytes without reopening the source or decoding its backup contents. */
function writeDesktopConfigBytes(path: string, bytes: Buffer, validateBeforeRename?: () => void): void {
  atomicWriteFileStreamed(path, descriptor => { writeFileSync(descriptor, bytes); }, validateBeforeRename ? { validateBeforeRename } : {});
}
