// storage/worker-store.ts — Persistence for worker results (SPEC-078 AC-14)
import { readJson, writeJson, projectDataDir } from './base-store.js';
import { withFileLock } from './file-mutex.js';
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const MAX_HISTORY_ENTRIES = 10;
// ---------------------------------------------------------------------------
// File paths
// ---------------------------------------------------------------------------
function workersDir(projectId) {
    return `${projectDataDir(projectId)}/workers`;
}
function latestFile(projectId, workerName) {
    return `${workersDir(projectId)}/${workerName}-latest.json`;
}
function historyFile(projectId, workerName) {
    return `${workersDir(projectId)}/${workerName}-history.json`;
}
function summaryFile(projectId) {
    return `${workersDir(projectId)}/summary.json`;
}
function configFile(projectId) {
    return `${workersDir(projectId)}/config.json`;
}
// ---------------------------------------------------------------------------
// Latest result
// ---------------------------------------------------------------------------
export async function saveLatestResult(projectId, result) {
    await writeJson(latestFile(projectId, result.workerName), result);
}
export async function getLatestResult(projectId, workerName) {
    const data = await readJson(latestFile(projectId, workerName), null);
    return data ?? undefined;
}
// ---------------------------------------------------------------------------
// History (circular buffer of last N results)
// ---------------------------------------------------------------------------
export async function appendHistory(projectId, result) {
    await withFileLock(historyFile(projectId, result.workerName), async () => {
        const history = await readJson(historyFile(projectId, result.workerName), []);
        const entry = {
            workerName: result.workerName,
            runAt: result.completedAt,
            durationMs: result.durationMs,
            status: result.status,
            findingsCount: result.findings.length,
            findings: result.findings,
        };
        history.push(entry);
        if (history.length > MAX_HISTORY_ENTRIES) {
            history.splice(0, history.length - MAX_HISTORY_ENTRIES);
        }
        await writeJson(historyFile(projectId, result.workerName), history);
    });
}
export async function getHistory(projectId, workerName) {
    return readJson(historyFile(projectId, workerName), []);
}
// ---------------------------------------------------------------------------
// Summary
// ---------------------------------------------------------------------------
export async function updateSummary(projectId, result, allWorkerNames) {
    await withFileLock(summaryFile(projectId), async () => {
        const existing = await readJson(summaryFile(projectId), {
            workers: [],
            lastUpdated: new Date().toISOString(),
        });
        // Update or add worker entry
        const workerIdx = existing.workers.findIndex((w) => w.name === result.workerName);
        const workerEntry = {
            name: result.workerName,
            enabled: true,
            lastRun: {
                runAt: result.completedAt,
                durationMs: result.durationMs,
                status: result.status,
                findingsCount: result.findings.length,
            },
        };
        if (workerIdx >= 0) {
            existing.workers[workerIdx] = workerEntry;
        }
        else {
            existing.workers.push(workerEntry);
        }
        // Ensure all workers appear
        for (const name of allWorkerNames) {
            if (!existing.workers.some((w) => w.name === name)) {
                existing.workers.push({ name, enabled: true });
            }
        }
        existing.lastUpdated = new Date().toISOString();
        await writeJson(summaryFile(projectId), existing);
    });
}
export async function getSummary(projectId) {
    return readJson(summaryFile(projectId), {
        workers: [],
        lastUpdated: new Date().toISOString(),
    });
}
// ---------------------------------------------------------------------------
// Project config overrides
// ---------------------------------------------------------------------------
export async function getProjectConfig(projectId) {
    return readJson(configFile(projectId), {
        overrides: {},
        lastUpdated: new Date().toISOString(),
    });
}
export async function saveProjectConfig(projectId, config) {
    await writeJson(configFile(projectId), config);
}
export async function updateOverride(projectId, workerName, override) {
    return withFileLock(configFile(projectId), async () => {
        const config = await getProjectConfig(projectId);
        config.overrides[workerName] = {
            ...config.overrides[workerName],
            ...override,
        };
        config.lastUpdated = new Date().toISOString();
        await saveProjectConfig(projectId, config);
        return config;
    });
}
//# sourceMappingURL=worker-store.js.map