const fs = require("fs");
const path = require("path");
const { spawnSync } = require("child_process");

const root = path.join(__dirname, "..");
const checks = [
  "scripts/verify-preflight.js",
  "scripts/verify-webui.js",
  "scripts/verify-ux-foundation.js",
  "scripts/verify-web-auth.js",
  "scripts/verify-feedback-system.js",
  "scripts/verify-logging.js",
  "scripts/verify-placeholders.js",
  "scripts/verify-release-metadata.js",
  "scripts/verify-update-system.js",
  "scripts/verify-production-diagnostics.js",
  "scripts/verify-plugin-update-preserves-data.js",
  "scripts/verify-safe-files.js",
  "scripts/verify-upload-security.js",
  "plugins/okf/tests/verify.js",
  "plugins/lumi_ai/tests/verify.js",
  "plugins/lumi_ai/tests/verify-tools.js",
  "plugins/lumi_ai_web_search/tests/verify.js",
  "plugins/lumi_transcription/tests/verify.js",
  "scripts/verify-assistant-panels.js",
  "scripts/verify-command-preview-confirmations.js",
  "scripts/verify-command-policies.js",
  "scripts/verify-destructive-actions.js",
  "scripts/verify-overlays.js",
  "scripts/verify-content-library.js",
  "scripts/verify-overlay-web-documents.js",
  "scripts/verify-webhooks.js"
];

function listJavaScript(directory, output = []) {
  for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
    if (["node_modules", ".git"].includes(entry.name) || entry.name.startsWith(".tmp-")) continue;
    const target = path.join(directory, entry.name);
    if (entry.isDirectory()) listJavaScript(target, output);
    else if (entry.name.endsWith(".js")) output.push(target);
  }
  return output;
}

function run(label, args) {
  console.log(`\n[verify] ${label}`);
  const result = spawnSync(process.execPath, args, { cwd: root, stdio: "inherit" });
  if (result.error) {
    console.error(`[verify] Unable to start ${label}: ${result.error.message}`);
    process.exit(result.status || 1);
  }
  if (result.status !== 0) {
    console.error(`[verify] ${label} failed with exit code ${result.status}.`);
    process.exit(result.status || 1);
  }
}

run("native dependency preflight", [path.join(root, "scripts", "verify-preflight.js")]);
const javaScriptFiles = ["src", "plugins", "scripts"]
  .flatMap((directory) => listJavaScript(path.join(root, directory)));
for (const file of javaScriptFiles) {
  run(`syntax: ${path.relative(root, file)}`, ["--check", file]);
}
for (const check of checks.slice(1)) run(check, [path.join(root, check)]);
console.log(`\nAll Lumi verification passed (${javaScriptFiles.length} JavaScript files, ${checks.length - 1} focused suites).`);
