import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { resolveFridayNextConfig } from "../config.js";
import { getHostOpenClawConfigSnapshot } from "../host-config.js";
import { getFridayNextRuntime } from "../runtime.js";
function currentHistoryDir() {
    const cfg = resolveFridayNextConfig(getHostOpenClawConfigSnapshot(getFridayNextRuntime().config));
    return cfg.historyDir;
}
export function getInstallationId(historyDir = currentHistoryDir()) {
    const file = path.join(historyDir, "installation-id");
    try {
        const existing = fs.readFileSync(file, "utf8").trim();
        if (existing)
            return existing;
    }
    catch {
        // Generate below.
    }
    const id = crypto.randomUUID();
    fs.mkdirSync(path.dirname(file), { recursive: true });
    const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
    fs.writeFileSync(tmp, `${id}\n`, { encoding: "utf8", mode: 0o600 });
    try {
        fs.renameSync(tmp, file);
    }
    catch {
        try {
            fs.unlinkSync(tmp);
        }
        catch {
            // ignore
        }
        const existing = fs.readFileSync(file, "utf8").trim();
        if (existing)
            return existing;
        throw new Error("Unable to initialize Friday Next installation id");
    }
    return id;
}
