import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import path from "node:path";
function emptyState() {
    return { version: 1, jobs: {} };
}
export class SolverState {
    filePath;
    data = emptyState();
    constructor(filePath) {
        this.filePath = filePath;
    }
    async load() {
        try {
            const parsed = JSON.parse(await readFile(this.filePath, "utf8"));
            this.data = parsed.version === 1 && parsed.jobs ? parsed : emptyState();
        }
        catch {
            this.data = emptyState();
        }
    }
    allJobs() {
        return Object.values(this.data.jobs).sort((left, right) => left.bountyId.localeCompare(right.bountyId));
    }
    jobForBounty(bountyId) {
        return this.data.jobs[bountyId];
    }
    hasLiveJobForBounty(bountyId) {
        const job = this.jobForBounty(bountyId);
        return Boolean(job && !["finalized", "expired", "dry-run"].includes(job.phase));
    }
    activeJobCount() {
        return this.allJobs().filter((job) => !["finalized", "expired", "dry-run"].includes(job.phase)).length;
    }
    async upsert(job) {
        const now = new Date().toISOString();
        this.data.jobs[job.bountyId] = {
            ...job,
            updatedAt: now
        };
        await this.save();
    }
    async save() {
        await mkdir(path.dirname(this.filePath), { recursive: true });
        const tempPath = `${this.filePath}.tmp`;
        await writeFile(tempPath, `${JSON.stringify(this.data, null, 2)}\n`, "utf8");
        await rename(tempPath, this.filePath);
    }
}
