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;
    // Five segments up from the compiled file
    // (`platform/plugins/graph-viewer/mcp/dist/lib/neo4j.js`) reaches
    // `platform/`, where the installer writes `config/.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.`);
    }
}
export function getDriver() {
    if (!driver) {
        // Refuse to default the URI — silent localhost:7687 has historically
        // crossed brand boundaries on shared devices.
        const uri = process.env.NEO4J_URI;
        if (!uri) {
            throw new Error("[graph-viewer] NEO4J_URI unset — refusing to default to bolt://localhost:7687");
        }
        const user = process.env.NEO4J_USER ?? "neo4j";
        const password = readPassword();
        console.error(`[graph-viewer] resolved neo4j_uri=${uri}`);
        driver = neo4j.driver(uri, neo4j.auth.basic(user, password));
    }
    return driver;
}
export function getSession() {
    return getDriver().session();
}
export async function closeDriver() {
    if (driver) {
        await driver.close();
        driver = null;
    }
}
//# sourceMappingURL=neo4j.js.map