"use strict";
/**
 * Port utilities for detecting process ownership
 */
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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.testLocalhostBinding = exports.waitForPortFree = exports.checkWindowsFirewall = exports.isCLIProxyProcess = exports.getPortProcess = void 0;
const child_process_1 = require("child_process");
const util_1 = require("util");
const execAsync = (0, util_1.promisify)(child_process_1.exec);
/**
 * Get process information for a port
 * @param port Port number to check
 * @returns Process info or null if port is free
 */
async function getPortProcess(port) {
    const isWindows = process.platform === 'win32';
    try {
        if (isWindows) {
            return await getPortProcessWindows(port);
        }
        else {
            return await getPortProcessUnix(port);
        }
    }
    catch {
        // If detection fails, return null (assume port is free)
        return null;
    }
}
exports.getPortProcess = getPortProcess;
/**
 * Unix/Linux/macOS implementation using lsof
 */
async function getPortProcessUnix(port) {
    try {
        const { stdout } = await execAsync(`lsof -i :${port} -sTCP:LISTEN -F pcn`, {
            timeout: 3000,
        });
        if (!stdout.trim()) {
            return null; // Port free
        }
        // Parse lsof -F output:
        // p<pid>
        // c<command>
        // n<network>
        const lines = stdout.trim().split('\n');
        let pid = null;
        let processName = null;
        for (const line of lines) {
            if (line.startsWith('p')) {
                pid = parseInt(line.substring(1), 10);
            }
            else if (line.startsWith('c')) {
                processName = line.substring(1);
            }
        }
        if (pid && processName) {
            return { pid, processName };
        }
        return null;
    }
    catch {
        return null;
    }
}
/**
 * Windows implementation using netstat
 */
async function getPortProcessWindows(port) {
    try {
        // netstat -ano finds PID, then tasklist gets process name
        const { stdout: netstatOut } = await execAsync(`netstat -ano | findstr :${port} | findstr LISTENING`, { timeout: 3000 });
        if (!netstatOut.trim()) {
            return null; // Port free
        }
        // Parse netstat output to get PID (last column)
        const match = netstatOut.match(/\s+(\d+)\s*$/m);
        if (!match) {
            return null;
        }
        const pid = parseInt(match[1], 10);
        // Get process name from PID
        const { stdout: tasklistOut } = await execAsync(`tasklist /FI "PID eq ${pid}" /NH`, {
            timeout: 3000,
        });
        const taskMatch = tasklistOut.match(/^([^\s]+)/);
        const processName = taskMatch ? taskMatch[1] : `PID-${pid}`;
        return { pid, processName };
    }
    catch {
        return null;
    }
}
/**
 * Check if process is CLIProxy
 * Uses prefix matching to handle Linux kernel's 15-char process name truncation
 * (e.g., 'cli-proxy-api-plus' becomes 'cli-proxy-api-p' in lsof/ps output)
 */
function isCLIProxyProcess(process) {
    if (!process) {
        return false;
    }
    const name = process.processName.toLowerCase();
    // All CLIProxy variants start with 'cli-proxy' or 'cliproxy'
    return name.startsWith('cli-proxy') || name.startsWith('cliproxy');
}
exports.isCLIProxyProcess = isCLIProxyProcess;
/**
 * Check if Windows Firewall might block a port
 * Returns immediately on non-Windows platforms
 */
async function checkWindowsFirewall(port) {
    if (process.platform !== 'win32') {
        return { checked: false, mayBlock: false, message: 'Not Windows' };
    }
    try {
        // Check for inbound rules allowing our port
        const { stdout } = await execAsync(`netsh advfirewall firewall show rule name=all dir=in | findstr /C:"LocalPort" | findstr /C:"${port}"`, { timeout: 5000 });
        // If we find the port in firewall rules, it's likely allowed
        if (stdout.trim()) {
            return { checked: true, mayBlock: false, message: `Port ${port} found in firewall rules` };
        }
        // Port not in rules - might be blocked
        return {
            checked: true,
            mayBlock: true,
            message: `Port ${port} may be blocked by Windows Firewall`,
            fixCommand: `netsh advfirewall firewall add rule name="CCS OAuth" dir=in action=allow protocol=TCP localport=${port}`,
        };
    }
    catch {
        // Command failed - could be no matching rules, assume might block
        return {
            checked: true,
            mayBlock: true,
            message: `Could not verify firewall rules for port ${port}`,
            fixCommand: `netsh advfirewall firewall add rule name="CCS OAuth" dir=in action=allow protocol=TCP localport=${port}`,
        };
    }
}
exports.checkWindowsFirewall = checkWindowsFirewall;
/**
 * Wait for a port to become free (no process listening)
 * @param port Port number to wait for
 * @param timeoutMs Maximum time to wait in milliseconds (default: 5000)
 * @param pollIntervalMs Interval between checks in milliseconds (default: 200)
 * @returns True if port became free, false if timeout
 */
async function waitForPortFree(port, timeoutMs = 5000, pollIntervalMs = 200) {
    const startTime = Date.now();
    while (Date.now() - startTime < timeoutMs) {
        const process = await getPortProcess(port);
        if (!process) {
            return true; // Port is free
        }
        // Wait before next check
        await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
    }
    return false; // Timeout reached
}
exports.waitForPortFree = waitForPortFree;
/**
 * Test if we can bind to localhost on a specific port
 * This verifies network stack is working and port is actually available
 */
async function testLocalhostBinding(port) {
    const net = await Promise.resolve().then(() => __importStar(require('net')));
    return new Promise((resolve) => {
        const server = net.createServer();
        server.once('error', (err) => {
            // H8: Close server to prevent fd leak on error path
            server.close(() => {
                if (err.code === 'EADDRINUSE') {
                    resolve({ success: false, message: `Port ${port} is already in use` });
                }
                else if (err.code === 'EACCES') {
                    resolve({ success: false, message: `Permission denied for port ${port}` });
                }
                else {
                    resolve({ success: false, message: `Cannot bind to port ${port}: ${err.message}` });
                }
            });
        });
        server.once('listening', () => {
            server.close(() => {
                resolve({ success: true, message: `Port ${port} is available` });
            });
        });
        // Try to bind to localhost only (like CLIProxyAPI does)
        server.listen(port, '127.0.0.1');
    });
}
exports.testLocalhostBinding = testLocalhostBinding;
//# sourceMappingURL=port-utils.js.map