#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const rtws_cli_1 = require("./bootstrap/rtws-cli");
const log_1 = require("./log");
const server_1 = require("./server");
const port_selection_1 = require("./server/port-selection");
const log = (0, log_1.createLogger)('server-debug');
function parseArgs(argv) {
    const out = {};
    for (let i = 0; i < argv.length; i++) {
        const arg = argv[i];
        if (arg === '-p' || arg === '--port') {
            out['p'] = argv[i + 1] ?? '';
            i++;
            continue;
        }
        if (arg.startsWith('--port=')) {
            out['p'] = arg.slice('--port='.length);
            continue;
        }
        if (arg === '-H' || arg === '--host' || arg === '-h') {
            out['H'] = argv[i + 1] ?? '';
            i++;
            continue;
        }
        if (arg.startsWith('--host=')) {
            out['H'] = arg.slice('--host='.length);
            continue;
        }
        if (arg === '--mode') {
            out['mode'] = argv[i + 1] ?? '';
            i++;
            continue;
        }
        if (arg.startsWith('--mode=')) {
            out['mode'] = arg.slice('--mode='.length);
            continue;
        }
    }
    return out;
}
async function main(argv = process.argv.slice(2)) {
    let parsed;
    try {
        parsed = (0, rtws_cli_1.extractGlobalRtwsChdir)({ argv });
        if (parsed.chdir !== undefined) {
            process.chdir(parsed.chdir);
        }
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        throw new Error(`Failed to apply server debug cwd: ${message}`);
    }
    const cliArgs = parseArgs(parsed.argv);
    const portSpecRaw = cliArgs['p'];
    const parsedPort = typeof portSpecRaw === 'string' ? (0, port_selection_1.parseWebuiPortSpec)(portSpecRaw) : undefined;
    if (portSpecRaw !== undefined && parsedPort === null) {
        throw new Error('Invalid --port value: expected a port number, optionally suffixed with + or -');
    }
    const modeRaw = cliArgs['mode'];
    if (modeRaw !== undefined && modeRaw !== 'dev' && modeRaw !== 'prod') {
        throw new Error("Invalid --mode value: expected 'dev' or 'prod'");
    }
    await (0, server_1.startServer)({
        port: parsedPort?.port,
        host: typeof cliArgs['H'] === 'string' && cliArgs['H'] !== '' ? cliArgs['H'] : undefined,
        mode: modeRaw,
        strictPort: parsedPort?.strictPort,
        portAutoDirection: parsedPort?.portAutoDirection,
        returnAfterListen: true,
    });
}
if (require.main === module) {
    main().catch((error) => {
        log.error('Web UI debug startup failed', error);
        process.exit(1);
    });
}
