import { mkdir, readFile, writeFile } from "fs/promises";
import { dirname, join } from "path";
import { getRunPath } from "../util/run-store.js";
export async function readCompletionSentinel(options) {
    const paths = [];
    if (options.runId) {
        paths.push(getRunPath(options.runId, "completion-sentinel.json", options.root));
    }
    if (options.goalId) {
        paths.push(join(options.root, ".omk", "goals", options.goalId, "completion-sentinel.json"));
    }
    for (const p of paths) {
        try {
            const content = await readFile(p, "utf-8");
            const parsed = JSON.parse(content);
            if (parsed && typeof parsed === "object") {
                return parsed;
            }
        }
        catch {
            // ignore missing or unreadable files
        }
    }
    return null;
}
export function hasCompletedEvidence(sentinel) {
    if (!sentinel)
        return false;
    if (sentinel.status !== "completed")
        return false;
    if (!sentinel.evidence || sentinel.evidence.length === 0)
        return false;
    return sentinel.evidence.every((e) => e.passed === true);
}
export async function writeCompletionSentinel(options) {
    const sentinel = {
        status: options.status,
        completedBy: options.completedBy,
        evidence: options.evidence,
        timestamp: new Date().toISOString(),
        runId: options.runId,
        goalId: options.goalId,
    };
    const path = options.runId
        ? getRunPath(options.runId, "completion-sentinel.json", options.root)
        : join(options.root, ".omk", "goals", options.goalId ?? "unknown", "completion-sentinel.json");
    await mkdir(dirname(path), { recursive: true });
    await writeFile(path, JSON.stringify(sentinel, null, 2) + "\n", "utf-8");
}
export async function markStoppedByLoopGuard(options) {
    await writeCompletionSentinel({
        root: options.root,
        runId: options.runId,
        goalId: options.goalId,
        status: "stopped",
        completedBy: "loop-guard",
        evidence: [
            {
                kind: "command",
                target: `loop-guard:${options.reason}`,
                passed: true,
                actual: `hash=${options.rawPromptHash}, confidence=${options.confidence}`,
            },
        ],
    });
}
