import fs from "node:fs";
import { readKitSqliteUserVersion } from "../../core/state/workspace-kit-sqlite.js";
export const CHECKPOINT_KIT_MIN_USER_VERSION = 9;
export function assertCheckpointKitSchema(dbAbsPath) {
    if (!fs.existsSync(dbAbsPath)) {
        return { ok: false, message: `SQLite database not found at ${dbAbsPath}` };
    }
    const uv = readKitSqliteUserVersion(dbAbsPath);
    if (uv < CHECKPOINT_KIT_MIN_USER_VERSION) {
        return {
            ok: false,
            message: `checkpoints require kit SQLite user_version >= ${CHECKPOINT_KIT_MIN_USER_VERSION} (current ${uv}); open the workspace DB with a current workspace-kit to migrate`
        };
    }
    return { ok: true };
}
function parseRow(r) {
    let manifest = [];
    try {
        const p = JSON.parse(String(r.manifest_json ?? "[]"));
        if (Array.isArray(p)) {
            manifest = p.filter((x) => typeof x === "string");
        }
    }
    catch {
        manifest = [];
    }
    let metadata = null;
    if (typeof r.metadata_json === "string" && r.metadata_json.trim()) {
        try {
            const o = JSON.parse(r.metadata_json);
            metadata = o && typeof o === "object" && !Array.isArray(o) ? o : null;
        }
        catch {
            metadata = null;
        }
    }
    const refKind = r.ref_kind === "stash" ? "stash" : "head";
    return {
        id: String(r.id),
        createdAt: String(r.created_at),
        taskId: r.task_id != null && String(r.task_id).trim() ? String(r.task_id) : null,
        actor: r.actor != null && String(r.actor).trim() ? String(r.actor) : null,
        label: r.label != null && String(r.label).trim() ? String(r.label) : null,
        actionType: String(r.action_type ?? "manual"),
        refKind,
        gitHeadSha: String(r.git_head_sha),
        secondaryRef: r.secondary_ref != null && String(r.secondary_ref).trim() ? String(r.secondary_ref) : null,
        manifest,
        metadata
    };
}
export function insertCheckpoint(db, row) {
    db.prepare(`INSERT INTO kit_task_checkpoints (
      id, created_at, task_id, actor, label, action_type, ref_kind, git_head_sha, secondary_ref, manifest_json, metadata_json
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(row.id, row.createdAt, row.taskId ?? null, row.actor ?? null, row.label ?? null, row.actionType, row.refKind, row.gitHeadSha, row.secondaryRef ?? null, JSON.stringify(row.manifest), row.metadata && Object.keys(row.metadata).length ? JSON.stringify(row.metadata) : null);
}
export function getCheckpointById(db, id) {
    const r = db.prepare("SELECT * FROM kit_task_checkpoints WHERE id = ?").get(id);
    return r ? parseRow(r) : undefined;
}
export function listCheckpoints(db, opts = {}) {
    const limit = Math.min(Math.max(opts.limit ?? 100, 1), 500);
    if (opts.taskId && opts.taskId.trim()) {
        const rows = db
            .prepare("SELECT * FROM kit_task_checkpoints WHERE task_id = ? ORDER BY created_at DESC LIMIT ?")
            .all(opts.taskId.trim(), limit);
        return rows.map(parseRow);
    }
    const rows = db
        .prepare("SELECT * FROM kit_task_checkpoints ORDER BY created_at DESC LIMIT ?")
        .all(limit);
    return rows.map(parseRow);
}
export function summarizeCheckpointsForDashboard(db) {
    const empty = {
        schemaVersion: 1,
        available: false,
        totalCount: 0,
        topRecent: []
    };
    if (!db) {
        return empty;
    }
    const uvRaw = db.pragma("user_version", { simple: true });
    const uv = typeof uvRaw === "number" ? uvRaw : Number(uvRaw);
    if (!Number.isFinite(uv) || uv < CHECKPOINT_KIT_MIN_USER_VERSION) {
        return empty;
    }
    try {
        const countRow = db.prepare("SELECT COUNT(*) AS c FROM kit_task_checkpoints").get();
        const totalCount = countRow ? Number(countRow.c) : 0;
        const topRecent = listCheckpoints(db, { limit: 15 }).map((row) => ({
            id: row.id,
            taskId: row.taskId,
            label: row.label,
            refKind: row.refKind,
            createdAt: row.createdAt,
            gitHeadSha: row.gitHeadSha
        }));
        return {
            schemaVersion: 1,
            available: true,
            totalCount,
            topRecent
        };
    }
    catch {
        return empty;
    }
}
