import { readdirSync, readFileSync, statSync } from "node:fs";
import { join, relative, resolve } from "node:path";
import { diagnose, formatWrn } from "../packages/syntax/src/index.ts";

const root = resolve(import.meta.dirname, "..");
const examples = join(root, "examples");
function walk(directory: string): string[] {
  return readdirSync(directory).flatMap((name) => {
    if (["node_modules", ".wrnexus", "dist", "build"].includes(name)) return [];
    const path = join(directory, name);
    return statSync(path).isDirectory() ? walk(path) : path.endsWith(".wrn") ? [path] : [];
  });
}

const failures: string[] = [];
const files = walk(examples);
for (const file of files) {
  const source = readFileSync(file, "utf8");
  for (const diagnostic of diagnose(source, { file, accessibility: true })) {
    if (diagnostic.severity !== "info")
      failures.push(`${relative(root, file)}: ${diagnostic.code} ${diagnostic.message}`);
  }
  const formatted = formatWrn(source);
  if (formatWrn(formatted) !== formatted)
    failures.push(`${relative(root, file)}: formatter is not idempotent`);
}

if (failures.length) throw new Error(`Example page validation failed:\n${failures.join("\n")}`);
console.log(
  `Validated ${files.length} example .wrn pages with compiler, accessibility, and formatter checks.`,
);
