import { appendFileSync, mkdirSync, existsSync } from "fs";
import { join } from "path";
import { redactSecrets } from "../orchestration/state-persister.js";
export function createAttemptRecorder(options) {
    const runsDir = options?.runsDir ?? ".omk/runs";
    function record(attempt) {
        const dir = join(runsDir, attempt.runId);
        if (!existsSync(dir)) {
            mkdirSync(dir, { recursive: true });
        }
        const filePath = join(dir, "attempts.jsonl");
        const line = JSON.stringify(redactSecrets(attempt)) + "\n";
        appendFileSync(filePath, line, "utf-8");
    }
    function startAttempt(runId, nodeId, attempt, providerId) {
        return {
            runId,
            nodeId,
            attempt,
            providerId,
            startedAt: new Date().toISOString(),
            success: false,
        };
    }
    function completeAttempt(record, success, exitCode, fallbackFrom, fallbackReason) {
        const completed = {
            ...record,
            completedAt: new Date().toISOString(),
            durationMs: Date.now() - new Date(record.startedAt).getTime(),
            success,
            exitCode,
            fallbackFrom,
            fallbackReason,
        };
        return completed;
    }
    return { record, startAttempt, completeAttempt };
}
