import { randomBytes, randomUUID } from 'crypto';
import { generatePairingCode } from './pairing-code.js';
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
import { homedir, hostname } from 'os';
import { join } from 'path';
const DIR = join(homedir(), '.cursorconnect');
const FILE = join(DIR, 'identity.json');
export function pairingIdentityPath() {
    return FILE;
}
export function loadPairingIdentity() {
    if (!existsSync(FILE))
        return null;
    try {
        const raw = readFileSync(FILE, 'utf-8');
        const data = JSON.parse(raw);
        if (!data.roomId || !data.clientToken)
            return null;
        return data;
    }
    catch {
        return null;
    }
}
export function ensurePairingIdentity(machineLabel) {
    const existing = loadPairingIdentity();
    if (existing) {
        return refreshPairingCode(existing, machineLabel);
    }
    const now = new Date().toISOString();
    const created = {
        roomId: randomUUID(),
        clientToken: randomBytes(32).toString('hex'),
        machineLabel: machineLabel?.trim() || defaultMachineLabel(),
        pairingCode: generatePairingCode(),
        pairingCodeExpiresAt: Date.now() + 10 * 60_000,
        createdAt: now,
        updatedAt: now,
    };
    savePairingIdentity(created);
    return created;
}
export function refreshPairingCode(identity, machineLabel) {
    const next = {
        ...identity,
        machineLabel: machineLabel?.trim() || identity.machineLabel,
        pairingCode: generatePairingCode(),
        pairingCodeExpiresAt: Date.now() + 10 * 60_000,
        updatedAt: new Date().toISOString(),
    };
    savePairingIdentity(next);
    return next;
}
export function rotateClientToken(identity) {
    const next = {
        ...identity,
        clientToken: randomBytes(32).toString('hex'),
        pairingCode: generatePairingCode(),
        pairingCodeExpiresAt: Date.now() + 10 * 60_000,
        updatedAt: new Date().toISOString(),
    };
    savePairingIdentity(next);
    return next;
}
function defaultMachineLabel() {
    return hostname().replace(/\.local$/i, '') || 'Mac';
}
export function savePairingIdentity(identity) {
    mkdirSync(DIR, { recursive: true, mode: 0o700 });
    writeFileSync(FILE, JSON.stringify(identity, null, 2), { mode: 0o600 });
    try {
        chmodSync(FILE, 0o600);
    }
    catch {
        /* ignore */
    }
}
export function buildPairUri(relayUrl, identity) {
    const base = relayUrl.replace(/\/$/, '');
    const q = new URLSearchParams({
        v: '1',
        relay: base,
        room: identity.roomId,
        token: identity.clientToken,
        label: identity.machineLabel,
    });
    return `cursorconnect://pair?${q.toString()}`;
}
