import type {
  ModelCatalogSource,
  ModelCompatibility,
  ProfileModelCatalog,
  ProfileModelCatalogEntry,
} from "@/domain";

type PartialCatalogEntry = Partial<ProfileModelCatalogEntry> & {
  adapter?: "claude" | "codex";
  modelId?: string;
  displayName?: string;
};

function compatibilityOf(value: unknown): ModelCompatibility {
  return value === "compatible" ||
    value === "unknown" ||
    value === "likelyTooRecent"
    ? value
    : "unknown";
}

function sourceOf(value: unknown): ModelCatalogSource {
  return value === "provider" ? "provider" : "catalogue";
}

function normalizeEntry(raw: PartialCatalogEntry): ProfileModelCatalogEntry {
  const modelId = raw.modelId ?? "";
  return {
    adapter: raw.adapter ?? "codex",
    modelId,
    displayName: raw.displayName ?? modelId,
    aliases: Array.isArray(raw.aliases) ? raw.aliases : [],
    recommended: Boolean(raw.recommended),
    compatibility: compatibilityOf(raw.compatibility),
    source: sourceOf(raw.source),
  };
}

export function normalizeProfileModelCatalog(raw: unknown): ProfileModelCatalog {
  if (Array.isArray(raw)) {
    return {
      models: raw.map((entry) => normalizeEntry(entry as PartialCatalogEntry)),
      cliVersion: null,
      warnings: [],
    };
  }

  const catalog =
    raw && typeof raw === "object"
      ? (raw as Partial<ProfileModelCatalog>)
      : {};

  return {
    models: Array.isArray(catalog.models)
      ? catalog.models.map((entry) => normalizeEntry(entry as PartialCatalogEntry))
      : [],
    cliVersion:
      typeof catalog.cliVersion === "string" ? catalog.cliVersion : null,
    warnings: Array.isArray(catalog.warnings)
      ? catalog.warnings.map(String)
      : [],
  };
}
