import path from "node:path";
import { archiveSidecarFile, persistModuleStateRow, readSidecarJsonFile } from "../state/module-state-sidecar-migration.js";
import { UnifiedStateDb } from "../state/unified-state-db.js";
import { planningSqliteDatabaseRelativePath } from "../../modules/task-engine/planning-config.js";
export const BUILD_PLAN_SESSION_SIDECAR_REL = path.join(".workspace-kit", "planning", "build-plan-session.json");
const MODULE_ID = "planning-build-session";
const STATE_SCHEMA = 1;
function dbRelativePath(workspacePath, effectiveConfig) {
    return planningSqliteDatabaseRelativePath({
        workspacePath,
        effectiveConfig
    });
}
function parseSession(raw) {
    if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
        return null;
    }
    const parsed = raw;
    if (parsed.schemaVersion !== 1 || typeof parsed.planningType !== "string") {
        return null;
    }
    if (typeof parsed.resumeCli !== "string") {
        return null;
    }
    return parsed;
}
export async function persistBuildPlanSession(workspacePath, snapshot, effectiveConfig) {
    const full = {
        schemaVersion: 1,
        updatedAt: new Date().toISOString(),
        ...snapshot
    };
    const rel = dbRelativePath(workspacePath, effectiveConfig);
    persistModuleStateRow({
        workspacePath,
        databaseRelativePath: rel,
        moduleId: MODULE_ID,
        stateSchemaVersion: STATE_SCHEMA,
        state: full
    });
    await archiveSidecarFile(workspacePath, BUILD_PLAN_SESSION_SIDECAR_REL);
}
export async function clearBuildPlanSession(workspacePath, effectiveConfig) {
    const rel = dbRelativePath(workspacePath, effectiveConfig);
    const db = new UnifiedStateDb(workspacePath, rel);
    db.deleteModuleState(MODULE_ID);
    await archiveSidecarFile(workspacePath, BUILD_PLAN_SESSION_SIDECAR_REL);
}
export async function readBuildPlanSession(workspacePath, effectiveConfig) {
    const rel = dbRelativePath(workspacePath, effectiveConfig);
    const db = new UnifiedStateDb(workspacePath, rel);
    const row = db.getModuleState(MODULE_ID);
    if (row?.state) {
        return parseSession(row.state);
    }
    const sidecar = await readSidecarJsonFile(workspacePath, BUILD_PLAN_SESSION_SIDECAR_REL);
    if (sidecar.ok) {
        const parsed = parseSession(sidecar.value);
        if (parsed) {
            persistModuleStateRow({
                workspacePath,
                databaseRelativePath: rel,
                moduleId: MODULE_ID,
                stateSchemaVersion: STATE_SCHEMA,
                state: parsed
            });
            await archiveSidecarFile(workspacePath, BUILD_PLAN_SESSION_SIDECAR_REL);
            return parsed;
        }
    }
    if ("corrupt" in sidecar && sidecar.corrupt) {
        await archiveSidecarFile(workspacePath, BUILD_PLAN_SESSION_SIDECAR_REL);
    }
    return null;
}
export function toDashboardPlanningSession(snap) {
    if (!snap)
        return null;
    return {
        schemaVersion: 1,
        updatedAt: snap.updatedAt,
        planningType: snap.planningType,
        outputMode: snap.outputMode,
        status: snap.status,
        completionPct: snap.completionPct,
        answeredCritical: snap.answeredCritical,
        totalCritical: snap.totalCritical,
        resumeCli: snap.resumeCli
    };
}
