import { createHash } from "node:crypto";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { spawnSync } from "node:child_process";

const sourceRepo = resolve(process.argv[2] ?? "../tmpa-site");
const targetRepo = resolve(process.argv[3] ?? ".");
const commit = "942cbb097eb3d662662f96a2269818ec9d7ca2ed";

const expectedSchemaDigests = {
  "governance-object.schema.json": "a2829cd7149c3054a52886365f2293a23106b636b0c52799739bfabdab1ff4fa",
  "lifecycle-profile.schema.json": "481a61ac2485bbaf15d90e9c5a255ad9ce6a55971190f0fe404856be4b10f993",
  "reader-result.schema.json": "4527df7096fe840b85b245e50d5cea576ff359d50a54d17c8873a7b4f458d431",
  "conformance-result.schema.json": "4b1ecebf83e62d2aa1aff0e79a0cd0ea0a85fbc14a426d5fe873ab40aefdc2fe",
};

function gitShow(sourcePath) {
  const result = spawnSync(
    "git",
    ["-c", `safe.directory=${sourceRepo.replaceAll("\\\\", "/")}`, "-C", sourceRepo, "show", `${commit}:${sourcePath}`],
    { encoding: null, maxBuffer: 32 * 1024 * 1024 },
  );
  if (result.status !== 0) {
    throw new Error(result.stderr.toString("utf8"));
  }
  return result.stdout;
}

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

function writeExact(targetPath, bytes) {
  const absolute = resolve(targetRepo, targetPath);
  mkdirSync(dirname(absolute), { recursive: true });
  writeFileSync(absolute, bytes);
}

const schemaNames = Object.keys(expectedSchemaDigests);
for (const name of schemaNames) {
  const bytes = gitShow(`docs/public/spec/tmpa/s1.0/${name}`);
  const actual = sha256(bytes);
  if (actual !== expectedSchemaDigests[name]) {
    throw new Error(`${name}: expected ${expectedSchemaDigests[name]}, got ${actual}`);
  }
  writeExact(`packages/codeflowmu-protocol/schemas/tmpa/s1.0/${name}`, bytes);
  writeExact(`tmpa-conformance/s1.0/upstream/schemas/${name}`, bytes);
}

const corpusFiles = [
  "README.md",
  "RELEASE-AUDIT.md",
  "canonicalization-profile.json",
  "profile.json",
  "fixtures.mjs",
  "reader.mjs",
  "runner.mjs",
  "product-evidence.json",
  ...Array.from({ length: 14 }, (_, index) =>
    `artifacts/criteria/C${String(index + 1).padStart(2, "0")}.json`,
  ),
];

for (const relative of corpusFiles) {
  const bytes = gitShow(`research/conformance/tmpa-core-s1.0/${relative}`);
  writeExact(`tmpa-conformance/s1.0/upstream/${relative}`, bytes);
}

const canonicalizationBytes = gitShow(
  "research/conformance/tmpa-core-s1.0/canonicalization-profile.json",
);
writeExact(
  "packages/codeflowmu-protocol/schemas/tmpa/s1.0/canonicalization-profile.json",
  canonicalizationBytes,
);

const fixtureBytes = gitShow(
  "research/conformance/tmpa-core-s1.0/fixtures.mjs",
);
const productFixtureBytes = Buffer.from(
  fixtureBytes
    .toString("utf8")
    .replace(
      "import { canonicalBytes, finalizeObject, sha256 } from './reader.mjs'",
      "import { canonicalBytes, finalizeTmpaObject as finalizeObject, tmpaSha256Digest as sha256 } from '../../packages/codeflowmu-runtime/src/tmpa/index.ts'",
    ),
  "utf8",
);
writeExact("tmpa-conformance/s1.0/product-fixtures.mjs", productFixtureBytes);

const s06Runner = readFileSync(
  resolve(targetRepo, "tmpa-conformance/s0.6/product-runner.ts"),
  "utf8",
);
const s1Runner = s06Runner
  .replaceAll("8989657e8fde6d2e55d7606ae0adacac14fec760", commit)
  .replaceAll("V1.6.0", "V1.8.0")
  .replaceAll("v1.6.0", "v1.8.0")
  .replaceAll("S0.6", "S1.0")
  .replaceAll("s0.6", "s1.0");
writeExact(
  "tmpa-conformance/s1.0/product-runner.ts",
  Buffer.from(s1Runner, "utf8"),
);

const imported = [
  ...schemaNames.map((name) => ({
    path: `docs/public/spec/tmpa/s1.0/${name}`,
    sha256: expectedSchemaDigests[name],
  })),
  ...corpusFiles.map((relative) => {
    const bytes = gitShow(`research/conformance/tmpa-core-s1.0/${relative}`);
    return {
      path: `research/conformance/tmpa-core-s1.0/${relative}`,
      sha256: sha256(bytes),
    };
  }),
];

writeExact(
  "tmpa-conformance/s1.0/upstream/import-lock.json",
  Buffer.from(`${JSON.stringify({ source_repo: "joinwell52-AI/joinwell52", source_branch: "agent/tmpa-s1.0-evidence-candidate", source_commit: commit, imported }, null, 2)}\n`, "utf8"),
);

process.stdout.write(`${JSON.stringify({ commit, imported }, null, 2)}\n`);
