import { createHash } from "node:crypto";

export function canonicalJson(value) {
  if (Array.isArray(value)) {
    return `[${value.map(canonicalJson).join(",")}]`;
  }

  if (value && typeof value === "object") {
    return `{${Object.keys(value)
      .sort()
      .map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`)
      .join(",")}}`;
  }

  return JSON.stringify(value);
}

export function sha256(value) {
  return createHash("sha256").update(value).digest("hex");
}

const manifest = Object.freeze({
  candidateId: "claims-denial-recommender-0.1.0",
  behavior: "recommendation-only",
  modelRoute: "local:deterministic-teaching-adapter",
  promptRevision: "recommend-denial-v1",
  policyRevision: "specialist-authority-v1",
  dataContractRevision: "claims-case-v1",
  toolContractRevision: "simulated-sor-v1",
  estimatedCostCadPerRun: 0.0012,
});

export const exactCandidate = Object.freeze({
  ...manifest,
  digest: sha256(canonicalJson(manifest)),
});

export function requestFingerprint(value) {
  return sha256(canonicalJson(value));
}
