import { createHash } from "node:crypto";
import { lstatSync, readdirSync, readFileSync } from "node:fs";
import { join, resolve } from "node:path";
import { pathToFileURL } from "node:url";

export function verifyInstallation(manifest, root) {
  if (manifest.schemaVersion !== 1 || manifest.scope !== "cli-bundled-skills"
      || !Array.isArray(manifest.files) || !manifest.files.length
      || manifest.fileCount !== manifest.files.length
      || !Array.isArray(manifest.skills)) {
    throw new Error("Expected an Ansight CLI release skill manifest, not the current website catalog.");
  }
  const expected = new Map();
  const skillNames = new Set();
  for (const file of manifest.files) {
    const parts = typeof file.path === "string" ? file.path.split("/") : [];
    if (parts.length < 2 || parts.some(part => !part || part === "." || part === ".." || /[\\:]/.test(part))
        || !/^[a-f0-9]{64}$/.test(file.sha256) || !Number.isSafeInteger(file.bytes) || file.bytes < 0
        || expected.has(file.path)) {
      throw new Error(`Invalid or duplicate manifest file: ${file.path}`);
    }
    expected.set(file.path, file);
    skillNames.add(parts[0]);
  }
  if (manifest.skills.length !== skillNames.size
      || new Set(manifest.skills).size !== skillNames.size
      || manifest.skills.some(skill => !skillNames.has(skill))
      || [...skillNames].some(skill => !expected.has(`${skill}/SKILL.md`))) {
    throw new Error("The skill list does not match the manifest files.");
  }

  const issues = [];
  const seen = new Set();
  const visit = (parts) => {
    const path = parts.join("/");
    const absolute = join(root, ...parts);
    let stat;
    try { stat = lstatSync(absolute); }
    catch (error) {
      if (error.code === "ENOENT") return;
      throw error;
    }
    if (stat.isSymbolicLink()) {
      issues.push(`Linked path: ${path}`);
    } else if (stat.isDirectory()) {
      for (const name of readdirSync(absolute).sort()) visit([...parts, name]);
    } else if (stat.isFile()) {
      seen.add(path);
      const file = expected.get(path);
      if (!file) issues.push(`Extra file: ${path}`);
      else {
        const bytes = readFileSync(absolute);
        const sha256 = createHash("sha256").update(bytes).digest("hex");
        if (bytes.length !== file.bytes || sha256 !== file.sha256) issues.push(`Changed file: ${path}`);
      }
    } else issues.push(`Unsupported file: ${path}`);
  };
  for (const skill of skillNames) visit([skill]);
  for (const path of expected.keys()) if (!seen.has(path)) issues.push(`Missing file: ${path}`);
  for (const entry of readdirSync(root, { withFileTypes: true })) {
    if (entry.name.startsWith("ansight-") && !skillNames.has(entry.name)) {
      issues.push(`Ansight entry absent from this release manifest: ${entry.name}`);
    }
  }
  return issues;
}

if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
  try {
    const [manifestPath, root] = process.argv.slice(2);
    if (!manifestPath || !root) throw new Error("Usage: node verify-skill-installation.mjs <release.skills.json> <agent-skills-root>");
    const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
    const issues = verifyInstallation(manifest, resolve(root));
    if (issues.length) {
      console.error(issues.join("\n"));
      process.exitCode = 1;
    } else console.log(`Verified ${manifest.fileCount} files for CLI ${manifest.version} (${manifest.buildNumber}, ${manifest.rid}).`);
  } catch (error) {
    console.error(error.message);
    process.exitCode = 1;
  }
}
