import { execFileSync } from "node:child_process";
import { openPlanningStores } from "./planning-open.js";
import { readTaskStateProjectionMeta, taskStateProjectionMetaTableAvailable, upsertTaskStateProjectionMeta } from "./task-state-projection-meta-store.js";
export function resolveGitHeadSha(workspacePath) {
    try {
        const out = execFileSync("git", ["rev-parse", "HEAD"], {
            cwd: workspacePath,
            encoding: "utf8",
            stdio: ["ignore", "pipe", "ignore"]
        }).trim();
        return out.length > 0 ? out : null;
    }
    catch {
        return null;
    }
}
export async function openPlanningStoresForTaskStateCache(ctx) {
    return openPlanningStores(ctx);
}
export function persistTaskStateProjectionDocument(planning, document, options) {
    planning.sqliteDual.seedFromDocuments(document, planning.sqliteDual.wishlistDocument);
    if (!planning.sqliteDual.relationalTasksEnabled) {
        planning.sqliteDual.enableRelationalPersistenceAndPersist();
        return;
    }
    planning.sqliteDual.persistSync({ persistScope: options?.persistScope ?? "full" });
}
export function upsertProjectionMetaAfterApply(planning, input) {
    const db = planning.sqliteDual.getDatabase();
    if (!taskStateProjectionMetaTableAvailable(db)) {
        return readTaskStateProjectionMeta(db);
    }
    return upsertTaskStateProjectionMeta(db, {
        backend: "git-event-log",
        appliedSequence: input.appliedSequence,
        sourceCommit: input.sourceCommit,
        projectionSchemaVersion: 1,
        syncStatus: input.syncStatus,
        updatedAt: input.updatedAt
    });
}
