#!/usr/bin/env node
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";

const project = path.resolve(process.argv[2] || ".");
const output = path.resolve(process.argv[3] || `${path.basename(project)}.zip`);
const readReport = name => {
  const file = path.join(project, name);
  if (!fs.existsSync(file)) return null;
  try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; }
};
const staticReport = readReport("audit-static.json");
const browserReport = readReport("audit-report.json");
if (!staticReport?.ok || !browserReport?.ok) {
  console.error("Packaging blocked: audit-static.json and audit-report.json must both exist and pass.");
  process.exit(1);
}
if (!fs.existsSync(project) || !fs.statSync(project).isDirectory()) {
  console.error(`Project directory not found: ${project}`);
  process.exit(2);
}
fs.mkdirSync(path.dirname(output), {recursive: true});
const python = String.raw`
import os, sys, zipfile
source, target = sys.argv[1], sys.argv[2]
excluded_dirs = {'.git','node_modules','.playwright','.playwright-cli','browser-profile','screenshots','__pycache__','.cache'}
excluded_suffixes = {'.key','.pem','.env','.log','.tmp'}
files = []
with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
    for root, dirs, names in os.walk(source):
        dirs[:] = [d for d in dirs if d not in excluded_dirs]
        for name in sorted(names):
            if name == '.DS_Store' or name.endswith(tuple(excluded_suffixes)) or name.startswith('.env'):
                continue
            full = os.path.join(root, name)
            rel = os.path.relpath(full, source)
            archive.write(full, rel)
            files.append(rel)
print(len(files))
`;
const zipped = spawnSync("python3", ["-c", python, project, output], {encoding: "utf8"});
if (zipped.status !== 0) {
  console.error(zipped.stderr || zipped.stdout || "zip creation failed");
  process.exit(zipped.status || 1);
}
const bytes = fs.readFileSync(output);
const sha256 = crypto.createHash("sha256").update(bytes).digest("hex");
fs.writeFileSync(`${output}.sha256`, `${sha256}  ${path.basename(output)}\n`);
console.log(JSON.stringify({ok: true, output, fileCount: Number.parseInt(zipped.stdout, 10), bytes: bytes.length, sha256}, null, 2));
