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

const policy = JSON.parse(readFileSync("ci/runner-isolation-policy.json", "utf8"));
const manifest = JSON.parse(readFileSync("tasks.manifest.json", "utf8"));
const workflow = readFileSync(".gitea/workflows/p0a-ci.yml", "utf8");
const gitAttributes = readFileSync(".gitattributes", "utf8");

const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
assert.match(gitAttributes, /^\*\s+text=auto\s+eol=lf\s*$/m);
const frozenBytePaths = [...Object.keys(manifest.source_hashes), "tasks.manifest.json"];
for (const path of frozenBytePaths) {
  assert.match(gitAttributes, new RegExp(`^/${escapeRegExp(path)}\\s+-text\\s*$`, "m"));
}
assert.match(gitAttributes, /^\/Dada-LowFi-Preview\/\*\*\s+-text\s*$/m);

for (const label of policy.required_labels) assert.match(workflow, new RegExp(`\\b${label}\\b`));
assert.doesNotMatch(workflow, /\bcorepack enable\b/);
assert.match(workflow, /Get-Content package\.json -Raw \| ConvertFrom-Json/);
assert.match(workflow, /pnpm --version/);
assert.match(workflow, /pnpm install --frozen-lockfile/);
assert.match(workflow, /DADA_EXTERNAL_MODE:\s*mock/);
assert.match(workflow, /pnpm test:all/);
assert.match(workflow, /pnpm package:portable/);
assert.match(workflow, /uses:\s+actions\/upload-artifact@v3\b/);
assert.doesNotMatch(workflow, /uses:\s+actions\/upload-artifact@v(?:[4-9]|\d{2,})\b/);

const forbiddenEnvironment = [
  "DADA_LOCAL_DATA_ROOT",
  "DADA_ASSET_ROOT",
  "AI_GATEWAY_API_KEY",
  "RESEND_API_KEY",
  "AMAP_API_KEY",
];
const present = forbiddenEnvironment.filter((name) => Object.hasOwn(process.env, name));
assert.deepEqual(present, [], `Isolated CI received forbidden environment inputs: ${present.join(", ")}`);

console.log(JSON.stringify({
  external_mode: policy.external_mode,
  forbidden_environment_inputs: present,
  required_labels: policy.required_labels,
  schema_version: policy.schema_version,
  status: "passed",
}, null, 2));
