import { lstat, readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { pathToFileURL } from "node:url";

// Exact-match experiment helper, NOT a general secret scanner or security verdict.
export async function scanCanaries(directory, markers, { include = () => true, maxBytes = 20 * 1024 * 1024 } = {}) {
  const entries = Object.entries(markers ?? {});
  if (!entries.length || entries.length > 100 || entries.some(([id, value]) =>
    !/^[a-z][a-z0-9_-]{0,63}$/.test(id) || typeof value !== "string" ||
    !/^THUNKLE_SYNTHETIC_CANARY_[A-Z0-9_]{8,128}$/.test(value))) {
    throw new Error("Use a nonempty map of named THUNKLE_SYNTHETIC_CANARY_ values only; never real credentials.");
  }
  if (new Set(entries.map(([, value]) => value)).size !== entries.length) {
    throw new Error("Canary values must be distinct.");
  }
  const root = path.resolve(directory);
  const stat = await lstat(root);
  if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error("Artifact root must be a real directory, not a symlink.");
  const matches = Object.fromEntries(entries.map(([id]) => [id, []]));
  let filesScanned = 0;
  async function walk(current) {
    for (const entry of (await readdir(current, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
      const file = path.join(current, entry.name);
      if (entry.isSymbolicLink()) throw new Error("Symlink encountered; refusing an incomplete or out-of-scope scan.");
      if (entry.isDirectory()) { await walk(file); continue; }
      if (!entry.isFile()) throw new Error("Unsupported file type encountered.");
      if (!include(file)) continue;
      if ((await lstat(file)).size > maxBytes) throw new Error("Artifact exceeds the scan size limit; result is incomplete.");
      const bytes = await readFile(file);
      filesScanned++;
      for (const [id, value] of entries) {
        if (bytes.includes(Buffer.from(value))) matches[id].push(path.relative(root, file).split(path.sep).join("/"));
      }
    }
  }
  await walk(root);
  if (!filesScanned) throw new Error("No eligible files; no observation can be made.");
  return { filesScanned, matches };
}

if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
  try {
    if (process.argv.length !== 4) throw new Error("Usage: node scan-canaries.mjs <artifact-directory> <synthetic-canaries.json>");
    const markers = JSON.parse(await readFile(process.argv[3], "utf8"));
    const result = await scanCanaries(process.argv[2], markers);
    const found = Object.values(result.matches).some(files => files.length);
    console.log(JSON.stringify({ status: found ? "LITERAL_FOUND" : "NO_LITERAL_MATCH", ...result,
      limitation: "Exact synthetic values in selected local files only. No match is not a security pass." }, null, 2));
    process.exitCode = found ? 1 : 0;
  } catch (error) {
    // Do not echo filenames, parser input or filesystem errors that may contain supplied secrets.
    const known = ["Use a nonempty", "Canary values", "Artifact root", "Symlink encountered", "Unsupported file", "Artifact exceeds", "No eligible", "Usage:"];
    console.error(JSON.stringify({ status: "INCONCLUSIVE", reason: known.some(s => error.message.startsWith(s)) ? error.message : "Unable to read artifact directory or canary map." }));
    process.exitCode = 2;
  }
}
