"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.execCleanup = execCleanup;
const fs_1 = require("fs");
const path_1 = require("path");
const readline_1 = require("readline");
const core_1 = require("@vsaf/core");
function dirSize(dirPath) {
    let total = 0;
    try {
        for (const entry of (0, fs_1.readdirSync)(dirPath, { withFileTypes: true })) {
            const full = (0, path_1.join)(dirPath, entry.name);
            if (entry.isDirectory()) {
                total += dirSize(full);
            }
            else {
                try {
                    total += (0, fs_1.statSync)(full).size;
                }
                catch { /* skip */ }
            }
        }
    }
    catch { /* skip */ }
    return total;
}
function formatBytes(bytes) {
    if (bytes < 1024)
        return `${bytes}B`;
    if (bytes < 1024 * 1024)
        return `${(bytes / 1024).toFixed(1)}KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
}
async function confirm(message) {
    const rl = (0, readline_1.createInterface)({ input: process.stdin, output: process.stdout });
    return new Promise((resolve) => {
        rl.question(`${message} (Y/n): `, (answer) => {
            rl.close();
            resolve(answer.trim().toLowerCase() !== 'n');
        });
    });
}
async function execCleanup(projectPath, opts) {
    const storageDir = (0, path_1.join)(projectPath, '.vsaf', 'storage');
    if (!(0, fs_1.existsSync)(storageDir)) {
        console.log('No storage directory found.');
        return;
    }
    const entries = [];
    if (opts.all) {
        // List ALL run directories
        for (const dir of (0, fs_1.readdirSync)(storageDir)) {
            if (!dir.startsWith('run-'))
                continue;
            const runDir = (0, path_1.join)(storageDir, dir);
            const store = new core_1.RunStore(storageDir);
            const run = store.load(dir);
            entries.push({
                runId: dir,
                workflow: run?.workflow ?? 'unknown',
                status: run?.status ?? 'unknown',
                startedAt: run?.startedAt ?? 'unknown',
                sizeBytes: dirSize(runDir),
            });
        }
    }
    else {
        // List only failed runs
        const store = new core_1.RunStore(storageDir);
        const failed = store.listFailed();
        for (const run of failed) {
            entries.push({
                ...run,
                sizeBytes: dirSize((0, path_1.join)(storageDir, run.runId)),
            });
        }
    }
    if (entries.length === 0) {
        console.log(opts.all ? 'No runs found in storage.' : 'No failed runs found.');
        return;
    }
    const totalBytes = entries.reduce((sum, e) => sum + e.sizeBytes, 0);
    const label = opts.all ? 'runs' : 'failed runs';
    console.log(`Found ${entries.length} ${label}:`);
    for (const e of entries) {
        console.log(`  ${e.runId}  ${e.workflow.padEnd(20)}  ${e.status.padEnd(10)}  ${e.startedAt.slice(0, 16)}  ${formatBytes(e.sizeBytes)}`);
    }
    console.log();
    if (opts.dryRun) {
        console.log(`[dry-run] Would delete ${entries.length} ${label}, freeing ~${formatBytes(totalBytes)}`);
        return;
    }
    const yes = await confirm(`Delete ${entries.length} ${label}?`);
    if (!yes) {
        console.log('Aborted.');
        return;
    }
    for (const e of entries) {
        (0, fs_1.rmSync)((0, path_1.join)(storageDir, e.runId), { recursive: true, force: true });
    }
    console.log(`Deleted ${entries.length} ${label}, freed ~${formatBytes(totalBytes)}`);
}
//# sourceMappingURL=cleanup.js.map