import fs from "node:fs/promises";
import path from "node:path";
import { UnifiedStateDb } from "./unified-state-db.js";
export const SIDECAR_MIGRATED_SUFFIX = ".migrated";
export function sidecarPath(workspacePath, relativePath) {
    return path.join(workspacePath, relativePath);
}
export async function readSidecarJsonFile(workspacePath, relativePath) {
    const fp = sidecarPath(workspacePath, relativePath);
    try {
        const rawText = await fs.readFile(fp, "utf8");
        const raw = JSON.parse(rawText);
        if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
            return { ok: false, corrupt: true };
        }
        return { ok: true, value: raw };
    }
    catch (e) {
        if (e.code === "ENOENT") {
            return { ok: false, missing: true };
        }
        return { ok: false, corrupt: true };
    }
}
/** Rename legacy sidecar so subsequent runs do not re-read it. */
export async function archiveSidecarFile(workspacePath, relativePath) {
    const fp = sidecarPath(workspacePath, relativePath);
    const archived = `${fp}${SIDECAR_MIGRATED_SUFFIX}`;
    try {
        await fs.rename(fp, archived);
    }
    catch (e) {
        if (e.code === "ENOENT") {
            return;
        }
        throw e;
    }
}
export function persistModuleStateRow(args) {
    const db = new UnifiedStateDb(args.workspacePath, args.databaseRelativePath);
    db.setModuleState(args.moduleId, args.stateSchemaVersion, args.state);
}
