"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.findFreeCallbackPort = findFreeCallbackPort;
exports.openInBrowser = openInBrowser;
exports.renderPage = renderPage;
const http = __importStar(require("node:http"));
const node_child_process_1 = require("node:child_process");
const CALLBACK_PORTS = [8899, 8900, 8901, 8902, 8910];
function tryListen(port) {
    return new Promise((resolve) => {
        const server = http.createServer();
        server.once('error', () => resolve(false));
        server.listen(port, '127.0.0.1', () => {
            server.close(() => resolve(true));
        });
    });
}
async function findFreeCallbackPort() {
    for (const port of CALLBACK_PORTS) {
        if (await tryListen(port))
            return port;
    }
    throw new Error(`No free local callback port available in [${CALLBACK_PORTS.join(', ')}]`);
}
function openInBrowser(url) {
    let cmd;
    let args;
    if (process.platform === 'darwin') {
        cmd = 'open';
        args = [url];
    }
    else if (process.platform === 'win32') {
        cmd = 'cmd';
        args = ['/c', 'start', '', url];
    }
    else {
        cmd = 'xdg-open';
        args = [url];
    }
    try {
        (0, node_child_process_1.execFile)(cmd, args, () => undefined);
        return true;
    }
    catch {
        return false;
    }
}
function renderPage(title, body) {
    return `<!DOCTYPE html><html><head><meta charset="utf-8"><title>${title}</title><style>body{font-family:sans-serif;max-width:480px;margin:80px auto;text-align:center}</style></head><body>${body}</body></html>`;
}
