import { randomBytes } from "node:crypto";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import path from "node:path";
import { patchtrailAppDataDir } from "../config/appDataPath.js";
import { LAUNCHER_FILES } from "./launcherConstants.js";
/**
 * The durable bridge capability token (PATCHTRAIL_BRIDGE_CAPABILITY_TOKEN).
 *
 * Unset, the bridge generates a random per-boot token that is never persisted —
 * fine for the bridge alone, but the launcher must know the token to mint the
 * local-UI handoff in-process. So the launcher owns it: a persisted, 0600
 * secret under the app data dir that it injects into the daemon's env. It is a
 * secret — never logged, never placed in argv or a URL, never synced/audited.
 * Persisting it (version-independently) also means it survives updates so the
 * user is not silently re-paired on every upgrade.
 */
export function loadOrCreateDurableBridgeToken(env = process.env) {
    // An explicit env token always wins (operator override / tests); we do not
    // persist it, mirroring the bridge's own precedence.
    const fromEnv = env.PATCHTRAIL_BRIDGE_CAPABILITY_TOKEN;
    if (fromEnv && fromEnv.length > 0)
        return fromEnv;
    const dir = patchtrailAppDataDir(env);
    const file = path.join(dir, LAUNCHER_FILES.bridgeToken);
    try {
        const existing = readFileSync(file, "utf8").trim();
        if (existing.length > 0)
            return existing;
    }
    catch {
        // Missing or unreadable → create a fresh durable token.
    }
    const token = randomBytes(32).toString("base64url");
    mkdirSync(dir, { recursive: true, mode: 0o700 });
    writeFileSync(file, `${token}\n`, { mode: 0o600 });
    return token;
}
