import crypto from "node:crypto";
import { importApprovalDecisionsJsonlIfNeeded, openKitAuditDatabase } from "../../core/state/kit-audit-sqlite.js";
export const APPROVAL_DECISION_SCHEMA_VERSION = 1;
export function computeDecisionFingerprint(taskId, decisionVerb, evidenceKey, editedSummary) {
    const norm = (editedSummary ?? "").trim();
    return crypto
        .createHash("sha256")
        .update([taskId, decisionVerb, evidenceKey, norm].join("\0"), "utf8")
        .digest("hex");
}
function withAuditDb(workspacePath, effectiveConfig, fn) {
    const db = openKitAuditDatabase(workspacePath, effectiveConfig);
    try {
        importApprovalDecisionsJsonlIfNeeded(db, workspacePath);
        return fn(db);
    }
    finally {
        db.close();
    }
}
export async function readDecisionFingerprints(workspacePath, effectiveConfig) {
    return withAuditDb(workspacePath, effectiveConfig, (db) => {
        const rows = db.prepare("SELECT fingerprint FROM kit_approval_decisions").all();
        return new Set(rows.map((r) => r.fingerprint));
    });
}
export async function appendDecisionRecord(workspacePath, record, effectiveConfig) {
    const full = {
        schemaVersion: APPROVAL_DECISION_SCHEMA_VERSION,
        timestamp: record.timestamp ?? new Date().toISOString(),
        ...record
    };
    withAuditDb(workspacePath, effectiveConfig, (db) => {
        db.prepare(`INSERT OR IGNORE INTO kit_approval_decisions
        (fingerprint, task_id, evidence_key, decision_verb, actor, recorded_at, edited_summary, policy_trace_json)
       VALUES (@fingerprint, @task_id, @evidence_key, @decision_verb, @actor, @recorded_at, @edited_summary, @policy_trace_json)`).run({
            fingerprint: full.fingerprint,
            task_id: full.taskId,
            evidence_key: full.evidenceKey,
            decision_verb: full.decisionVerb,
            actor: full.actor,
            recorded_at: full.timestamp,
            edited_summary: full.editedSummary ?? null,
            policy_trace_json: full.policyTraceRef ? JSON.stringify(full.policyTraceRef) : null
        });
    });
}
export async function listApprovalDecisionRecords(workspacePath, effectiveConfig) {
    return withAuditDb(workspacePath, effectiveConfig, (db) => {
        const rows = db
            .prepare(`SELECT fingerprint, task_id, evidence_key, decision_verb, actor, recorded_at, edited_summary, policy_trace_json
         FROM kit_approval_decisions ORDER BY recorded_at ASC`)
            .all();
        return rows.map((r) => ({
            schemaVersion: APPROVAL_DECISION_SCHEMA_VERSION,
            fingerprint: r.fingerprint,
            taskId: r.task_id,
            evidenceKey: r.evidence_key,
            decisionVerb: r.decision_verb,
            actor: r.actor,
            timestamp: r.recorded_at,
            editedSummary: r.edited_summary ?? undefined,
            policyTraceRef: r.policy_trace_json
                ? JSON.parse(r.policy_trace_json)
                : undefined
        }));
    });
}
