import { mkdir, readFile, writeFile } from "fs/promises";
import { join } from "path";
import { getProjectRoot, pathExists } from "../util/fs.js";
const STORE_DIR = ".omk/awareness";
const STORE_FILE = "notices.jsonl";
function getStorePath() {
    return join(getProjectRoot(), STORE_DIR, STORE_FILE);
}
async function ensureStoreDir() {
    const dir = join(getProjectRoot(), STORE_DIR);
    await mkdir(dir, { recursive: true });
}
function generateId() {
    return `ntc_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
}
async function readLines() {
    const path = getStorePath();
    if (!(await pathExists(path)))
        return [];
    try {
        const content = await readFile(path, "utf-8");
        const lines = content.split("\n").filter((line) => line.trim().length > 0);
        const notices = [];
        for (const line of lines) {
            try {
                const parsed = JSON.parse(line);
                if (isNotice(parsed))
                    notices.push(parsed);
            }
            catch {
                // skip corrupt lines
            }
        }
        return notices;
    }
    catch {
        return [];
    }
}
function isNotice(value) {
    if (!value || typeof value !== "object")
        return false;
    const obj = value;
    return (typeof obj.id === "string" &&
        typeof obj.createdAt === "string" &&
        typeof obj.source === "string" &&
        typeof obj.type === "string" &&
        typeof obj.severity === "string" &&
        typeof obj.confidence === "number" &&
        typeof obj.summary === "string" &&
        Array.isArray(obj.evidenceRefs) &&
        typeof obj.suggestedAction === "string");
}
export async function saveNotice(notice) {
    const full = {
        ...notice,
        id: generateId(),
        createdAt: new Date().toISOString(),
    };
    await ensureStoreDir();
    const path = getStorePath();
    const line = JSON.stringify(full) + "\n";
    await writeFile(path, line, { flag: "a", encoding: "utf-8" });
    return full;
}
export async function listNotices() {
    return readLines();
}
export async function getNotice(id) {
    const notices = await readLines();
    return notices.find((n) => n.id === id);
}
export async function resolveNotice(id) {
    const path = getStorePath();
    const notices = await readLines();
    const target = notices.find((n) => n.id === id);
    if (!target)
        return undefined;
    const updated = {
        ...target,
        resolved: true,
        resolvedAt: new Date().toISOString(),
    };
    const lines = notices.map((n) => (n.id === id ? JSON.stringify(updated) : JSON.stringify(n)));
    await writeFile(path, lines.join("\n") + "\n", "utf-8");
    return updated;
}
export async function listActiveNotices() {
    const notices = await readLines();
    return notices.filter((n) => !n.resolved);
}
