import { readFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import path from "node:path";
import { createHash } from "node:crypto";

const root = path.dirname(fileURLToPath(import.meta.url));
const actual = JSON.parse(await readFile(path.join(root, "outputs", "public-history.json"), "utf8"));
const expected = JSON.parse(await readFile(path.join(root, "expected-snapshot.json"), "utf8"));
const manifest = JSON.parse(await readFile(path.join(root, "outputs", "manifest.json"), "utf8"));

const checks = [
  ["repository.createdAt", actual.repository.createdAt, expected.repositoryCreatedAt],
  ["milestone.firstStarAt", actual.milestone.firstStarAt, expected.firstStarAt],
  ["milestone.star100At", actual.milestone.star100At, expected.star100At],
  ["milestone.star130At", actual.milestone.star130At, expected.star130At],
  ["stateAtStar130.commitsReachableFromDefaultBranch", actual.stateAtStar130.commitsReachableFromDefaultBranch, expected.commitsAtStar130],
  ["stateAtStar130.mergedPullRequests", actual.stateAtStar130.mergedPullRequests, expected.mergedPullRequestsAtStar130],
  ["stateAtStar130.openedNonPullIssues", actual.stateAtStar130.openedNonPullIssues, expected.openedNonPullIssuesAtStar130],
  ["stateAtStar130.publishedGitHubReleases", actual.stateAtStar130.publishedGitHubReleases, expected.publishedReleasesAtStar130],
  ["starsByUtcDayThrough130.length", actual.starsByUtcDayThrough130.length, 11],
  ["starsByUtcDayThrough130 final cumulative", actual.starsByUtcDayThrough130.at(-1)?.cumulative, 130],
];

for (const file of manifest.files) {
  const bytes = await readFile(path.join(root, ...file.path.split("/")));
  const digest = createHash("sha256").update(bytes).digest("hex");
  checks.push([`sha256(${file.path})`, digest, file.sha256]);
}

let failed = false;
for (const [name, found, wanted] of checks) {
  const ok = found === wanted;
  process.stdout.write(`${ok ? "PASS" : "FAIL"} ${name}: ${JSON.stringify(found)}\n`);
  failed ||= !ok;
}

if (failed) {
  process.stderr.write("\nThe live API no longer reconstructs the checked July 20 snapshot exactly. This can happen if an early stargazer unstars the repository or GitHub data changes. Preserve the archived output and investigate before updating the article.\n");
  process.exitCode = 1;
}
