"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadJobs = loadJobs;
exports.getJob = getJob;
exports.saveJob = saveJob;
exports.deleteJob = deleteJob;
exports.loadRuns = loadRuns;
exports.getRun = getRun;
exports.saveRun = saveRun;
exports.pruneAllRuns = pruneAllRuns;
exports.getLatestRun = getLatestRun;
exports.getRecentFailureCount = getRecentFailureCount;
const node_fs_1 = require("node:fs");
const node_os_1 = require("node:os");
const node_path_1 = require("node:path");
const PREFS_DIR = (0, node_path_1.join)((0, node_os_1.homedir)(), ".cockpit");
const JOBS_FILE = (0, node_path_1.join)(PREFS_DIR, "scheduled-jobs.json");
const RUNS_DIR = (0, node_path_1.join)(PREFS_DIR, "job-runs");
function ensureDir(dir) {
    (0, node_fs_1.mkdirSync)(dir, { recursive: true });
}
function runsFile(jobId) {
    return (0, node_path_1.join)(RUNS_DIR, `${jobId}.json`);
}
function loadJobs() {
    try {
        const data = JSON.parse((0, node_fs_1.readFileSync)(JOBS_FILE, "utf-8"));
        return data.jobs || [];
    }
    catch {
        return [];
    }
}
function getJob(id) {
    return loadJobs().find((j) => j.id === id);
}
function saveJob(job) {
    const jobs = loadJobs();
    const idx = jobs.findIndex((j) => j.id === job.id);
    if (idx >= 0) {
        jobs[idx] = job;
    }
    else {
        jobs.push(job);
    }
    ensureDir(PREFS_DIR);
    (0, node_fs_1.writeFileSync)(JOBS_FILE, JSON.stringify({ jobs }, null, 2) + "\n");
}
function deleteJob(id) {
    const jobs = loadJobs();
    const filtered = jobs.filter((j) => j.id !== id);
    if (filtered.length === jobs.length)
        return false;
    ensureDir(PREFS_DIR);
    (0, node_fs_1.writeFileSync)(JOBS_FILE, JSON.stringify({ jobs: filtered }, null, 2) + "\n");
    const rf = runsFile(id);
    try {
        if ((0, node_fs_1.existsSync)(rf)) {
            const { unlinkSync } = require("node:fs");
            unlinkSync(rf);
        }
    }
    catch { }
    return true;
}
function loadRuns(jobId) {
    try {
        const data = JSON.parse((0, node_fs_1.readFileSync)(runsFile(jobId), "utf-8"));
        return data.runs || [];
    }
    catch {
        return [];
    }
}
function getRun(jobId, runId) {
    return loadRuns(jobId).find((r) => r.id === runId);
}
function saveRun(run) {
    const runs = loadRuns(run.jobId);
    const idx = runs.findIndex((r) => r.id === run.id);
    if (idx >= 0) {
        runs[idx] = run;
    }
    else {
        runs.push(run);
    }
    const job = getJob(run.jobId);
    const maxAgeDays = job?.retentionDays ?? 90;
    pruneRuns(runs, 500, maxAgeDays);
    ensureDir(RUNS_DIR);
    (0, node_fs_1.writeFileSync)(runsFile(run.jobId), JSON.stringify({ runs }, null, 2) + "\n");
}
function pruneRuns(runs, maxCount, maxAgeDays) {
    const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;
    for (let i = runs.length - 1; i >= 0; i--) {
        if (runs[i].startedAt < cutoff) {
            runs.splice(i, 1);
        }
    }
    if (runs.length > maxCount) {
        runs.sort((a, b) => b.startedAt - a.startedAt);
        runs.length = maxCount;
    }
}
function pruneAllRuns() {
    const jobs = loadJobs();
    for (const job of jobs) {
        const runs = loadRuns(job.id);
        const before = runs.length;
        pruneRuns(runs, 500, job.retentionDays ?? 90);
        if (runs.length < before) {
            ensureDir(RUNS_DIR);
            (0, node_fs_1.writeFileSync)(runsFile(job.id), JSON.stringify({ runs }, null, 2) + "\n");
        }
    }
}
function getLatestRun(jobId) {
    const runs = loadRuns(jobId);
    if (runs.length === 0)
        return undefined;
    return runs.reduce((latest, r) => (r.startedAt > latest.startedAt ? r : latest));
}
function getRecentFailureCount() {
    const jobs = loadJobs();
    let count = 0;
    for (const job of jobs) {
        const latest = getLatestRun(job.id);
        if (latest && (latest.status === "failure" || latest.status === "timeout")) {
            count++;
        }
    }
    return count;
}
