import fs from "node:fs";
import path from "node:path";
import { GoogleCalendarClient } from "../calendar/google-calendar.js";
import { GmailEmailClient } from "../email/gmail-email.js";
import { GoogleDriveClient } from "../drive/google-drive.js";
import { getE2ERunDir, listRecentRunIds } from "./artifacts.js";
import { aggregateStatus } from "./reporter.js";
export function loadCleanupItems(runId) {
    const file = path.join(getE2ERunDir(runId), "cleanup.json");
    if (!fs.existsSync(file))
        return [];
    try {
        return JSON.parse(fs.readFileSync(file, "utf-8"));
    }
    catch {
        return [];
    }
}
export function saveCleanupItems(runId, items) {
    const dir = getE2ERunDir(runId);
    fs.mkdirSync(dir, { recursive: true });
    fs.writeFileSync(path.join(dir, "cleanup.json"), `${JSON.stringify(items, null, 2)}\n`, "utf-8");
}
export async function runCleanupForRun(config, runId) {
    const items = loadCleanupItems(runId);
    if (items.length === 0) {
        return { status: "passed", items: [], message: "No cleanup items registered" };
    }
    const calendar = safeClient(() => new GoogleCalendarClient(config));
    const gmail = safeClient(() => new GmailEmailClient(config));
    const drive = safeClient(() => new GoogleDriveClient(config));
    const orderedItems = [...items].sort((a, b) => cleanupPriority(a) - cleanupPriority(b));
    for (const item of orderedItems) {
        if (item.cleanupStatus === "done")
            continue;
        try {
            switch (item.type) {
                case "calendar_event":
                    if (calendar)
                        await calendar.deleteEvent(item.id);
                    break;
                case "gmail_message":
                    if (gmail)
                        await gmail.archive(item.id);
                    break;
                case "drive_file":
                    if (drive)
                        await drive.deleteFile(item.id);
                    break;
                case "local_file":
                    if (fs.existsSync(item.id))
                        fs.unlinkSync(item.id);
                    break;
                default:
                    break;
            }
            item.cleanupStatus = "done";
        }
        catch {
            item.cleanupStatus = "failed";
        }
    }
    saveCleanupItems(runId, items);
    const status = aggregateStatus(items.map((item) => {
        if (item.cleanupStatus === "done")
            return "passed";
        if (item.cleanupStatus === "failed")
            return "failed";
        return "warning";
    }));
    return {
        status,
        items,
        message: items.some((item) => item.cleanupStatus === "failed") ? "Some cleanup items failed" : undefined,
    };
}
export function formatCleanupList(limit = 10) {
    const runIds = listRecentRunIds(limit);
    if (runIds.length === 0)
        return "No recent E2E runs found.";
    const lines = ["Recent E2E runs with cleanup state:", ""];
    runIds.forEach((runId, index) => {
        const items = loadCleanupItems(runId);
        const pending = items.filter((item) => item.cleanupStatus === "pending").length;
        const failed = items.filter((item) => item.cleanupStatus === "failed").length;
        lines.push(`${index + 1}. ${runId}`);
        lines.push(`   cleanup: pending=${pending}, failed=${failed}, total=${items.length}`);
    });
    lines.push("", "Commands:", "- /e2e cleanup latest", "- /e2e cleanup <runId>", "- /e2e cleanup --all-stale");
    return lines.join("\n");
}
function cleanupPriority(item) {
    if (item.type === "drive_file" && item.details?.role === "folder")
        return 20;
    return 10;
}
export function hasFailedCleanupItems(runId) {
    return loadCleanupItems(runId).some((item) => item.cleanupStatus === "failed");
}
function safeClient(factory) {
    try {
        return factory();
    }
    catch {
        return null;
    }
}
//# sourceMappingURL=cleanup.js.map