import { randomUUID } from "node:crypto";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { hostname } from "node:os";
import path from "node:path";
import { patchtrailAppDataDir } from "../config/appDataPath.js";
import { LAUNCHER_FILES } from "./launcherConstants.js";
function isIdentity(value) {
    if (typeof value !== "object" || value === null)
        return false;
    const v = value;
    return (typeof v.workspaceId === "string" &&
        v.workspaceId.length > 0 &&
        typeof v.userSessionId === "string" &&
        v.userSessionId.length > 0 &&
        typeof v.deviceId === "string" &&
        v.deviceId.length > 0);
}
/**
 * Loads the persisted install identity, creating and persisting one on first
 * run. The file is written 0600 (the directory 0700) since it identifies the
 * local install; it carries no secret, but stays user-private by default.
 */
export function loadOrCreateInstallIdentity(env = process.env) {
    const dir = patchtrailAppDataDir(env);
    const file = path.join(dir, LAUNCHER_FILES.identity);
    try {
        const parsed = JSON.parse(readFileSync(file, "utf8"));
        if (isIdentity(parsed))
            return parsed;
    }
    catch {
        // Missing or unreadable → fall through and create a fresh identity.
    }
    const identity = {
        workspaceId: `ws-local-${randomUUID()}`,
        userSessionId: `local-${randomUUID()}`,
        deviceId: `local-${hostname()}`,
    };
    mkdirSync(dir, { recursive: true, mode: 0o700 });
    writeFileSync(file, `${JSON.stringify(identity, null, 2)}\n`, {
        mode: 0o600,
    });
    return identity;
}
