"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getInboxMessages = getInboxMessages;
exports.getUnreadCount = getUnreadCount;
exports.addInboxMessage = addInboxMessage;
exports.markRead = markRead;
exports.markAllRead = markAllRead;
exports.deleteInboxMessage = deleteInboxMessage;
exports.clearInbox = clearInbox;
exports.parseInboxBlock = parseInboxBlock;
exports.parseErrorBlock = parseErrorBlock;
const node_fs_1 = require("node:fs");
const node_os_1 = require("node:os");
const node_path_1 = __importDefault(require("node:path"));
const uuid_1 = require("uuid");
const notifications_1 = require("./notifications");
const INBOX_DIR = node_path_1.default.join((0, node_os_1.homedir)(), ".cockpit");
const INBOX_FILE = node_path_1.default.join(INBOX_DIR, "inbox.jsonl");
function ensureDir() {
    if (!(0, node_fs_1.existsSync)(INBOX_DIR))
        (0, node_fs_1.mkdirSync)(INBOX_DIR, { recursive: true });
}
function readAll() {
    if (!(0, node_fs_1.existsSync)(INBOX_FILE))
        return [];
    const raw = (0, node_fs_1.readFileSync)(INBOX_FILE, "utf-8");
    const messages = [];
    for (const line of raw.split("\n")) {
        if (!line.trim())
            continue;
        try {
            messages.push(JSON.parse(line));
        }
        catch { }
    }
    return messages;
}
function writeAll(messages) {
    ensureDir();
    (0, node_fs_1.writeFileSync)(INBOX_FILE, messages.map((m) => JSON.stringify(m)).join("\n") + "\n");
}
function getInboxMessages() {
    return readAll().sort((a, b) => b.createdAt - a.createdAt);
}
function getUnreadCount() {
    return readAll().filter((m) => !m.read).length;
}
function addInboxMessage(msg) {
    const messages = readAll();
    const entry = {
        id: (0, uuid_1.v4)(),
        title: msg.title,
        body: msg.body,
        priority: msg.priority || "info",
        jobId: msg.jobId,
        jobName: msg.jobName,
        runId: msg.runId,
        createdAt: Date.now(),
        read: false,
    };
    messages.push(entry);
    writeAll(messages);
    (0, notifications_1.dispatchNotification)({
        title: entry.title,
        body: entry.body,
        priority: entry.priority,
        source: "inbox",
        url: `/inbox/${entry.id}`,
        providerIds: msg.notifyProviders,
    });
    return entry;
}
function markRead(id) {
    const messages = readAll();
    const msg = messages.find((m) => m.id === id);
    if (!msg)
        return false;
    msg.read = true;
    writeAll(messages);
    return true;
}
function markAllRead() {
    const messages = readAll();
    for (const m of messages)
        m.read = true;
    writeAll(messages);
}
function deleteInboxMessage(id) {
    const messages = readAll();
    const idx = messages.findIndex((m) => m.id === id);
    if (idx === -1)
        return false;
    messages.splice(idx, 1);
    writeAll(messages);
    return true;
}
function clearInbox() {
    writeAll([]);
}
const INBOX_BLOCK_RE = /```cockpit-inbox\s*\n([\s\S]*?)\n```/;
function parseInboxBlock(text) {
    const match = INBOX_BLOCK_RE.exec(text);
    if (!match)
        return null;
    try {
        const parsed = JSON.parse(match[1]);
        if (typeof parsed.title !== "string" || typeof parsed.body !== "string")
            return null;
        return { title: parsed.title, body: parsed.body, priority: parsed.priority };
    }
    catch {
        return null;
    }
}
const ERROR_BLOCK_RE = /```cockpit-error\s*\n([\s\S]*?)\n```/;
function parseErrorBlock(text) {
    const match = ERROR_BLOCK_RE.exec(text);
    if (!match)
        return null;
    try {
        const parsed = JSON.parse(match[1]);
        if (typeof parsed.error !== "string")
            return null;
        return { error: parsed.error, details: parsed.details };
    }
    catch {
        return null;
    }
}
