import { readOptionalExpectedPlanningGeneration } from "./mutation-utils.js";
/** Runtime persistence is SQLite-only; config must not set `tasks.persistenceBackend` to `json`. */
export function getTaskPersistenceBackend(_config) {
    return "sqlite";
}
export function planningTaskStoreRelativePath(ctx) {
    const tasks = ctx.effectiveConfig?.tasks;
    if (!tasks || typeof tasks !== "object" || Array.isArray(tasks)) {
        return undefined;
    }
    const p = tasks.storeRelativePath;
    return typeof p === "string" && p.trim().length > 0 ? p.trim() : undefined;
}
export function planningSqliteDatabaseRelativePath(ctx) {
    const tasks = ctx.effectiveConfig?.tasks;
    if (!tasks || typeof tasks !== "object" || Array.isArray(tasks)) {
        return ".workspace-kit/tasks/workspace-kit.db";
    }
    const p = tasks.sqliteDatabaseRelativePath;
    return typeof p === "string" && p.trim().length > 0
        ? p.trim()
        : ".workspace-kit/tasks/workspace-kit.db";
}
export function planningStrictValidationEnabled(ctx) {
    const tasks = ctx.effectiveConfig?.tasks;
    if (!tasks || typeof tasks !== "object" || Array.isArray(tasks)) {
        return false;
    }
    return tasks.strictValidation === true;
}
export function getPlanningGenerationPolicy(ctx) {
    const tasks = ctx.effectiveConfig?.tasks;
    if (!tasks || typeof tasks !== "object" || Array.isArray(tasks)) {
        return "off";
    }
    const raw = tasks.planningGenerationPolicy;
    if (raw === "warn" || raw === "require") {
        return raw;
    }
    return "off";
}
/** Gate mutating planning-store commands when tasks.planningGenerationPolicy is warn or require. */
export function enforcePlanningGenerationPolicy(policy, args) {
    const hasToken = readOptionalExpectedPlanningGeneration(args) !== undefined;
    if (policy === "require" && !hasToken) {
        return {
            ok: false,
            code: "planning-generation-required",
            message: "tasks.planningGenerationPolicy is 'require': include expectedPlanningGeneration from a prior read (planningGeneration on responses); retry after re-read when you get planning-generation-mismatch"
        };
    }
    if (policy === "warn" && !hasToken) {
        return {
            ok: true,
            warnings: [
                "tasks.planningGenerationPolicy is 'warn': expectedPlanningGeneration omitted — last-writer-wins; pass the token from your last read for strong consistency"
            ]
        };
    }
    return { ok: true };
}
export function mergePlanningGenerationPolicyWarnings(data, warnings) {
    if (!warnings?.length) {
        return;
    }
    const prior = data.planningGenerationPolicyWarnings;
    const merged = [
        ...(Array.isArray(prior) ? prior.filter((x) => typeof x === "string") : []),
        ...warnings
    ];
    data.planningGenerationPolicyWarnings = merged;
}
