import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { invalidateCodexModelsCache, syncCatalogModels } from "./catalog/retained-sync";
import type { ComboCatalogOmission } from "./catalog/aggregation";
import { getCodexHome } from "./paths";
import { withCatalogWriteSerialization, CatalogWritePermitRefusal } from "./catalog-write-serialization";
import { replaceCodexModelsCache } from "./internal/catalog-writer";
import type { OcxConfig } from "../types";
import type { CodexCatalogSyncOptions } from "./catalog/retained-sync";

export interface CodexCatalogRefreshResult {
  added: number;
  path: string;
  catalogExists: boolean;
  catalogWritten: boolean;
  cacheSynced: boolean;
  comboOmissions: ComboCatalogOmission[];
  refreshOutcome?: "committed" | "refused";
  /**
   * Desired OFF observed under K during the catalog commit, or a write refused because it would
   * empty routed namespaces config.json does not back (#6529); no cache write either way.
   */
  skippedReason?: "desired_disabled" | "unbacked_routed_removal" | "foreign_owner" | "owner_unknown";
  protectedRoutedNamespaces?: number;
}

interface RefreshDeps {
  syncCatalogModels: typeof syncCatalogModels;
  invalidateCodexModelsCache: typeof invalidateCodexModelsCache;
  existsSync: typeof existsSync;
}

const defaultDeps: RefreshDeps = {
  syncCatalogModels,
  invalidateCodexModelsCache,
  existsSync,
};

export function syncCodexModelsCacheFromCatalog(catalogPath: string): void {
  const owningCodexHome = getCodexHome();
  const outcome = withCatalogWriteSerialization(owningCodexHome, permit =>
    replaceCodexModelsCache(permit, owningCodexHome, {
      path: join(owningCodexHome, "models_cache.json"),
      content: readFileSync(catalogPath, "utf8"),
    }), { intent: "cache", writer: "cache-from-catalog" });
  if (outcome.kind === "unavailable") throw new CatalogWritePermitRefusal(`Catalog cache synchronization unavailable (${outcome.reason}).`);
}

/**
 * Rebuild Codex's on-disk model catalog and force Codex's models cache stale
 * when a catalog file exists. The cache must keep Codex's fetched_at/client_version
 * wrapper shape; writing the raw catalog back here makes app-server/TUI refreshes
 * inconsistent with the CLI models-manager cache path.
 */
export async function refreshCodexModelCatalog(
  config: OcxConfig,
  deps: RefreshDeps = defaultDeps,
  options?: CodexCatalogSyncOptions,
): Promise<CodexCatalogRefreshResult> {
  const result = await deps.syncCatalogModels(config, options);
  const catalogExists = deps.existsSync(result.path);
  const catalogWritten = result.catalogWritten === true;
  const comboOmissions = result.comboOmissions ?? [];
  if (result.skippedReason !== undefined || result.refreshOutcome === "refused") {
    // The commit path observed OFF, or an unbacked routed removal, under K. Invalidate
    // nothing: rewriting the models cache here would be exactly the write the skip refused.
    return { ...result, catalogExists, catalogWritten: false, cacheSynced: false, comboOmissions };
  }
  if (!catalogExists) {
    return { ...result, catalogExists, catalogWritten: false, cacheSynced: false, comboOmissions };
  }
  const cacheSynced = deps.invalidateCodexModelsCache(options);
  return { ...result, catalogExists, catalogWritten, cacheSynced, comboOmissions };
}
