// cli/src/memory.ts
import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
import { join } from "node:path";
import { homedir } from "node:os";
const DIR = join(homedir(), ".kaogongpro");
const FILE = join(DIR, "memory.json");
function empty() {
    return { prefs: {}, watched: [], events: [] };
}
export function memoryPath() { return FILE; }
export function loadMemory() {
    try {
        return JSON.parse(readFileSync(FILE, "utf-8"));
    }
    catch {
        return empty();
    }
}
function save(state) {
    if (!existsSync(DIR))
        mkdirSync(DIR, { recursive: true });
    writeFileSync(FILE, JSON.stringify(state, null, 2));
}
export function setPrefs(updates) {
    const state = loadMemory();
    for (const [k, v] of Object.entries(updates)) {
        if (v === undefined || v === "")
            continue;
        state.prefs[k] =
            k === "score" || k === "grassroots_years" ? Number(v) : String(v);
    }
    save(state);
    return state;
}
export function addWatched(positionId, year, label, note) {
    const state = loadMemory();
    state.watched.push({
        position_id: positionId, year, label,
        added_at: new Date().toISOString(), note,
    });
    save(state);
    return state;
}
export function logEvent(type, detail) {
    const state = loadMemory();
    state.events.push({ at: new Date().toISOString(), type, detail });
    if (state.events.length > 200)
        state.events = state.events.slice(-200);
    save(state);
    return state;
}
export function clearMemory() {
    const state = empty();
    save(state);
    return state;
}
