import neo4j from "neo4j-driver";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
let driver = null;
function readPassword() {
    if (process.env.NEO4J_PASSWORD)
        return process.env.NEO4J_PASSWORD;
    const passwordFile = resolve(process.env.PLATFORM_ROOT ?? resolve(import.meta.dirname, "../../../.."), "config/.neo4j-password");
    try {
        return readFileSync(passwordFile, "utf-8").trim();
    }
    catch {
        throw new Error(`Neo4j password not found. Expected at ${passwordFile} or in NEO4J_PASSWORD env var.`);
    }
}
function getSession() {
    if (!driver) {
        // NEO4J_URI must be explicit. Silent default to:7687 was the
        // vector for the orphan data in Maxy's DB from a realagent install.
        const uri = process.env.NEO4J_URI;
        if (!uri) {
            throw new Error("[telegram/message-history] NEO4J_URI unset — refusing to default to bolt://localhost:7687");
        }
        const user = process.env.NEO4J_USER ?? "neo4j";
        const password = readPassword();
        console.error(`[telegram/message-history] resolved neo4j_uri=${uri}`);
        driver = neo4j.driver(uri, neo4j.auth.basic(user, password));
    }
    return driver.session();
}
export async function messageHistory(params) {
    const { channel, chatId, accountId, limit = 20 } = params;
    const session = getSession();
    try {
        const conditions = ["m.accountId = $accountId"];
        const queryParams = { accountId, limit: neo4j.int(limit) };
        if (channel) {
            conditions.push("m.channel = $channel");
            queryParams.channel = channel;
        }
        if (chatId) {
            conditions.push("m.chatId = $chatId");
            queryParams.chatId = chatId;
        }
        const query = `
      MATCH (m:Communication)
      WHERE ${conditions.join(" AND ")}
      RETURN m
      ORDER BY m.dateSent DESC
      LIMIT $limit
    `;
        const result = await session.run(query, queryParams);
        return result.records.map((record) => {
            const m = record.get("m").properties;
            return {
                channel: m.channel,
                chatId: m.chatId,
                role: m.role,
                content: m.content,
                timestamp: m.dateSent,
            };
        });
    }
    finally {
        await session.close();
    }
}
//# sourceMappingURL=message-history.js.map