import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
const STATE_FILE = "agentvault.json";
const LEGACY_STATE_FILE = "secure-channel.json";
export async function saveState(dataDir, state) {
    await mkdir(dataDir, { recursive: true });
    const filePath = join(dataDir, STATE_FILE);
    await writeFile(filePath, JSON.stringify(state, null, 2), "utf-8");
    // Clean up legacy file after migration
    try {
        await rm(join(dataDir, LEGACY_STATE_FILE));
    }
    catch {
        // Already removed or never existed
    }
}
/**
 * Load raw persisted state from disk.
 * Returns the raw parsed JSON — caller is responsible for migration
 * from legacy format to current PersistedState.
 *
 * Checks agentvault.json first, falls back to secure-channel.json
 * for backward compatibility. Auto-migrates on first legacy load.
 */
export async function loadState(dataDir) {
    // Try new filename first
    const filePath = join(dataDir, STATE_FILE);
    try {
        const raw = await readFile(filePath, "utf-8");
        return JSON.parse(raw);
    }
    catch {
        // Fall through to legacy
    }
    // Fall back to legacy filename
    const legacyPath = join(dataDir, LEGACY_STATE_FILE);
    try {
        const raw = await readFile(legacyPath, "utf-8");
        const parsed = JSON.parse(raw);
        // Auto-migrate: write to new filename, remove legacy
        await mkdir(dataDir, { recursive: true });
        await writeFile(filePath, JSON.stringify(parsed, null, 2), "utf-8");
        await rm(legacyPath);
        return parsed;
    }
    catch {
        return null;
    }
}
export async function clearState(dataDir) {
    // Remove both files to cover migration edge cases
    for (const filename of [STATE_FILE, LEGACY_STATE_FILE]) {
        try {
            await rm(join(dataDir, filename));
        }
        catch {
            // File doesn't exist — nothing to clear
        }
    }
}
//# sourceMappingURL=state.js.map