import assert from "node:assert/strict";
import { existsSync, readFileSync } from "node:fs";
import test from "node:test";

import { frozenPackages } from "../../scripts/frozen-versions.mjs";

const expectedFiles = [
  "NuGet.Config",
  "pnpm-lock.yaml",
  "pnpm-workspace.yaml",
  "tsconfig.base.json",
  "apps/web/package.json",
  "apps/web/src/toolchain-probe.tsx",
  "apps/api/package.json",
  "apps/api/src/app.ts",
  "apps/worker/package.json",
  "apps/worker/src/worker.ts",
  "packages/shared-contracts/package.json",
  "packages/shared-contracts/src/index.ts",
  "scripts/validate-tdd-trace.mjs",
  "scripts/native-smoke.mjs",
  "supervisor/Dada.Supervisor/Dada.Supervisor.csproj",
];

function readJson(path) {
  return JSON.parse(readFileSync(path, "utf8"));
}

test("TASK-WP0-01 has no unresolved task dependency", () => {
  const manifest = readJson("tasks.manifest.json");
  const task = manifest.tasks.find((item) => item.task_id === "TASK-WP0-01");
  assert.ok(task, "TASK-WP0-01 must exist in tasks.manifest.json");
  assert.deepEqual(task.dependencies.task_ids, []);
  assert.deepEqual(task.dependencies.work_packages, []);
  assert.equal(task.dependencies.source_text, "无");
});

test("TDD-WP0-DEP-001 frozen toolchain contract is implemented", () => {
  const problems = [];

  for (const path of expectedFiles) {
    if (!existsSync(path)) problems.push(`missing file: ${path}`);
  }

  for (const [path, sections] of Object.entries(frozenPackages)) {
    if (!existsSync(path)) continue;
    const packageJson = readJson(path);
    for (const [section, packages] of Object.entries(sections)) {
      for (const [name, version] of Object.entries(packages)) {
        const actual = packageJson[section]?.[name];
        if (actual !== version) {
          problems.push(`${path} ${section}.${name}: expected ${version}, got ${actual ?? "missing"}`);
        }
      }
    }
  }

  assert.deepEqual(problems, []);
});
