import { createHash } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";

import { generateAgentOpenApi } from "../src/contracts/openapi.js";

const canonicalJson = (value: unknown) => `${JSON.stringify(value, null, 2)}\n`;
const document = generateAgentOpenApi();
const payload = canonicalJson(document);
const sha256 = createHash("sha256").update(payload).digest("hex");
const manifestPayload = canonicalJson({
  contract_version: "1.0.0",
  contracts: {
    agent: {
      file: "agent-v1.openapi.json",
      sha256,
    },
  },
});

if (process.argv.includes("--check")) {
  const currentContract = await readFile(
    "contracts/agent-v1.openapi.json",
    "utf8",
  );
  const currentManifest = await readFile("contracts/manifest.json", "utf8");
  if (currentContract !== payload || currentManifest !== manifestPayload) {
    throw new Error(
      "Agent OpenAPI contract is stale: run `bun run contract:generate`",
    );
  }
  console.log(`validated Agent OpenAPI contract (${sha256})`);
} else {
  await mkdir("contracts", { recursive: true });
  await writeFile("contracts/agent-v1.openapi.json", payload, "utf8");
  await writeFile("contracts/manifest.json", manifestPayload, "utf8");
  console.log(`generated Agent OpenAPI contract (${sha256})`);
}
