/**
 * runs command — utilities for working with run-anchored artifacts on disk.
 *
 * The unified artifact writer (D0033 M4) lays artifacts down under
 * `.ailf/results/captures/runs/{runId}/…`. Downstream tooling (CI archivers,
 * external consumers that used to parse the legacy collector tarball) still
 * want a single-file bundle. `runs export --format tarball` reproduces that
 * bundle from the existing tree — no re-materialisation, just a tar of the
 * files already written.
 *
 * The on-disk layout is identical to what the legacy FilesystemArtifactCollector
 * produced (same paths, same filenames), so the tarball shape is stable for
 * existing consumers.
 *
 * @see docs/decisions/D0033-unified-run-anchored-artifact-capture.md
 */
import { spawnSync } from "node:child_process";
import { existsSync, mkdirSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { Command } from "commander";
const DEFAULT_ARTIFACTS_DIR = ".ailf/results/captures";
function resolveArtifactsDir(flag) {
    return resolve(flag ?? process.env.AILF_ARTIFACTS_DIR ?? DEFAULT_ARTIFACTS_DIR);
}
function resolveOutputPath(explicit, artifactsDir, runId) {
    if (explicit)
        return resolve(explicit);
    return resolve(artifactsDir, `runs-${runId}.tar.gz`);
}
function exportTarball(opts) {
    if (opts.format !== "tarball") {
        console.error(`❌ Unsupported --format "${opts.format}". Supported: tarball.`);
        return 2;
    }
    const artifactsDir = resolveArtifactsDir(opts.artifactsDir);
    const runRoot = resolve(artifactsDir, "runs", opts.runId);
    if (!existsSync(runRoot)) {
        console.error(`❌ No artifacts on disk for run "${opts.runId}" at ${runRoot}`);
        console.error("   Set --artifacts-dir / AILF_ARTIFACTS_DIR or check the runId.");
        return 1;
    }
    const outputPath = resolveOutputPath(opts.output, artifactsDir, opts.runId);
    const outputDir = dirname(outputPath);
    mkdirSync(outputDir, { recursive: true });
    // Spawn system tar — the unified tree is byte-for-byte identical to the
    // legacy collector's output, so `tar -czf` produces a tarball with the
    // same file list consumers depended on.
    const tar = spawnSync("tar", ["-czf", outputPath, "-C", resolve(artifactsDir, "runs"), opts.runId], { stdio: "inherit" });
    if (tar.status !== 0) {
        console.error(`❌ tar exited with status ${tar.status}`);
        return tar.status ?? 1;
    }
    console.log(`  ✅ Exported ${runRoot} → ${outputPath}`);
    return 0;
}
export function createRunsCommand() {
    const cmd = new Command("runs").description("Utilities for working with run-anchored artifact trees on disk");
    cmd
        .command("export")
        .description("Export a run's artifact tree to a portable archive. Only `--format tarball` is supported.")
        .requiredOption("--run-id <runId>", "Run id to export (required)")
        .option("--format <fmt>", "Output format (currently only: tarball)", "tarball")
        .option("--artifacts-dir <path>", "Override the root directory containing runs/{runId}/… (default: .ailf/results/captures)")
        .option("-o, --output <path>", "Output archive path (default: {artifacts-dir}/runs-{runId}.tar.gz)")
        .action((opts) => {
        const code = exportTarball(opts);
        if (code !== 0)
            process.exit(code);
    });
    return cmd;
}
