import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import {
  readManifest,
  supportedPrograms,
  verifyCanonicalManifest,
} from "./release-policy.mjs";

const metadata = JSON.parse(readFileSync(0, "utf8"));
const manifest = verifyCanonicalManifest(readManifest());
const expected = supportedPrograms(manifest);
const packagesById = new Map(metadata.packages.map((pkg) => [pkg.id, pkg]));

assert.ok(Array.isArray(metadata.workspace_members), "workspace_members must be present");
assert.equal(
  metadata.workspace_members.length,
  expected.length,
  "compiler-resolved workspace member count must match the candidate allowlist",
);

const actual = metadata.workspace_members
  .map((id) => {
    const pkg = packagesById.get(id);
    assert.ok(pkg, `workspace package is missing from metadata: ${id}`);
    return pkg;
  })
  .sort((left, right) => left.name.localeCompare(right.name));

assert.deepEqual(
  actual.map((pkg) => pkg.name),
  expected,
  "compiler-resolved workspace members must exactly match supported candidates",
);

for (const pkg of actual) {
  const canonical = manifest.programs.find((entry) => entry.name === pkg.name);
  assert.ok(canonical, `unknown compiler-resolved workspace package: ${pkg.name}`);
  assert.ok(
    pkg.manifest_path.endsWith(`/${canonical.cargoManifestPath}`),
    `${pkg.name} resolved from a noncanonical manifest path`,
  );

  const localDependencies = pkg.dependencies.filter(
    (dependency) => dependency.path !== null && dependency.path !== undefined,
  );
  assert.deepEqual(localDependencies, [], `${pkg.name} has a local path dependency`);

  const anchor = pkg.dependencies.filter((dependency) => dependency.name === "anchor-lang");
  assert.equal(anchor.length, 1, `${pkg.name} must resolve exactly one anchor-lang dependency`);
  assert.equal(anchor[0].req, "=0.32.1", `${pkg.name} must pin anchor-lang exactly`);
}

console.log(`Cargo metadata gate passed for ${actual.length} supported candidates.`);
