/**
 * Pack processed agent output directories into a single ZIP archive.
 *
 * Replaces the shell-based pack.sh — collects output/ directories from
 * all processed agents and bundles them with the summary report.
 *
 * Usage:
 *   visionclaw pack-data <data-root> [--batch-date=YYYYMMDD]
 */
import fs from "node:fs";
import path from "node:path";
import { execSync } from "node:child_process";
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
const DATE_PATTERN = /^\d{8}T\d{6}$/;
/** Copy a directory recursively. */
function copyDir(src, dest) {
    fs.mkdirSync(dest, { recursive: true });
    for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
        const srcPath = path.join(src, entry.name);
        const destPath = path.join(dest, entry.name);
        if (entry.isDirectory()) {
            copyDir(srcPath, destPath);
        }
        else if (entry.isFile()) {
            fs.copyFileSync(srcPath, destPath);
        }
    }
}
function parsePackArgs(args) {
    let dataRoot = "";
    let batchDate = "";
    for (const arg of args) {
        if (arg.startsWith("--batch-date=")) {
            batchDate = arg.slice("--batch-date=".length);
        }
        else if (!arg.startsWith("-") && !dataRoot) {
            dataRoot = arg;
        }
    }
    if (!batchDate) {
        const now = new Date();
        batchDate = [
            String(now.getFullYear()),
            String(now.getMonth() + 1).padStart(2, "0"),
            String(now.getDate()).padStart(2, "0"),
        ].join("");
    }
    if (!dataRoot) {
        console.error("Usage: visionclaw pack-data <data-root> [--batch-date=YYYYMMDD]\n" +
            "\n" +
            "  <data-root>           Root directory containing agent data folders\n" +
            "  --batch-date=YYYYMMDD Date label for the ZIP filename (default: today)");
        process.exit(1);
    }
    return { dataRoot, batchDate };
}
export function runPackData(args) {
    const opts = parsePackArgs(args);
    if (!fs.existsSync(opts.dataRoot) || !fs.statSync(opts.dataRoot).isDirectory()) {
        console.error(`Not a directory: ${opts.dataRoot}`);
        process.exit(1);
    }
    const zipName = `visionclaw-trace-data-batch-${opts.batchDate}`;
    const zipFile = path.join(opts.dataRoot, `${zipName}.zip`);
    const staging = path.join(opts.dataRoot, ".pack-staging");
    // Clean up any previous staging
    if (fs.existsSync(staging)) {
        fs.rmSync(staging, { recursive: true, force: true });
    }
    const packDir = path.join(staging, zipName);
    fs.mkdirSync(packDir, { recursive: true });
    let count = 0;
    for (const agentEntry of fs.readdirSync(opts.dataRoot, { withFileTypes: true })) {
        if (!agentEntry.isDirectory() || agentEntry.name.startsWith("."))
            continue;
        const agentDir = path.join(opts.dataRoot, agentEntry.name);
        for (const dateEntry of fs.readdirSync(agentDir, { withFileTypes: true })) {
            if (!dateEntry.isDirectory() || !DATE_PATTERN.test(dateEntry.name))
                continue;
            const outputDir = path.join(agentDir, dateEntry.name, "output");
            if (!fs.existsSync(outputDir))
                continue;
            const dest = path.join(packDir, agentEntry.name);
            console.log(`  ADD ${agentEntry.name} (${dateEntry.name})`);
            copyDir(outputDir, dest);
            count++;
        }
    }
    if (count === 0) {
        console.log("No output folders found. Run the pipeline first.");
        fs.rmSync(staging, { recursive: true, force: true });
        return;
    }
    // Include summary report if available
    const summaryPath = path.join(opts.dataRoot, "summary-report.json");
    if (fs.existsSync(summaryPath)) {
        fs.copyFileSync(summaryPath, path.join(packDir, "summary-report.json"));
        console.log("  ADD summary-report.json");
    }
    else {
        console.log("  WARN summary-report.json not found, run summary-data first");
    }
    // Create ZIP
    if (fs.existsSync(zipFile)) {
        fs.unlinkSync(zipFile);
    }
    execSync(`cd "${staging}" && zip -r "${zipFile}" "${zipName}"`, {
        stdio: "pipe",
    });
    // Clean up staging
    fs.rmSync(staging, { recursive: true, force: true });
    console.log("");
    console.log(`Packed ${count} agents into: ${path.basename(zipFile)}`);
    const stat = fs.statSync(zipFile);
    const sizeMB = (stat.size / (1024 * 1024)).toFixed(1);
    console.log(`  Size: ${sizeMB} MB`);
    console.log(`  Path: ${zipFile}`);
}
//# sourceMappingURL=pack.js.map