import path from "node:path";
import { archiveSidecarFile, persistModuleStateRow, readSidecarJsonFile } from "../../core/state/module-state-sidecar-migration.js";
import { UnifiedStateDb } from "../../core/state/unified-state-db.js";
import { planningSqliteDatabaseRelativePath } from "../task-engine/planning-config.js";
export const BEHAVIOR_INTERVIEW_SESSION_SIDECAR_REL = path.join(".workspace-kit", "agent-behavior", "interview-session.json");
const MODULE_ID = "agent-behavior-interview";
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)
        return null;
    if (typeof parsed.stepIndex !== "number")
        return null;
    if (!parsed.answers || typeof parsed.answers !== "object")
        return null;
    return parsed;
}
export async function persistBehaviorInterviewSession(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, BEHAVIOR_INTERVIEW_SESSION_SIDECAR_REL);
}
export async function clearBehaviorInterviewSession(workspacePath, effectiveConfig) {
    const rel = dbRelativePath(workspacePath, effectiveConfig);
    const db = new UnifiedStateDb(workspacePath, rel);
    db.deleteModuleState(MODULE_ID);
    await archiveSidecarFile(workspacePath, BEHAVIOR_INTERVIEW_SESSION_SIDECAR_REL);
}
export async function readBehaviorInterviewSession(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, BEHAVIOR_INTERVIEW_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, BEHAVIOR_INTERVIEW_SESSION_SIDECAR_REL);
            return parsed;
        }
    }
    if ("corrupt" in sidecar && sidecar.corrupt) {
        await archiveSidecarFile(workspacePath, BEHAVIOR_INTERVIEW_SESSION_SIDECAR_REL);
    }
    return null;
}
