import { test, expect } from '@playwright/test';

// Private-network detection test.
// Captures both Playwright-level request events and CDP Network events where
// available. Keep under `tests/` when you want CI or local runs to check for
// accidental private-network requests.

function isPrivateHostname(hostname: string) {
    if (!hostname) return false;
    if (hostname === 'localhost' || hostname.endsWith('.localhost')) return true;
    if (/^(127)\.|^(10)\.|^(192\.168)\.|^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(hostname)) return true;
    return false;
}

test('detect private/local network requests and PNA preflights', async ({ page }) => {
    const privateRequests: Array<any> = [];
    const cdpPrivateRequests: Array<any> = [];
    const consoleMessages: string[] = [];

    page.on('console', (msg) => consoleMessages.push(`${msg.type()}: ${msg.text()}`));

    page.on('request', (request) => {
        try {
            const url = new URL(request.url());
            const headers = request.headers();
            const hostname = url.hostname;
            const pnaHeader = (headers['access-control-request-private-network'] || headers['Access-Control-Request-Private-Network']);

            if (isPrivateHostname(hostname) || pnaHeader === 'true') {
                privateRequests.push({ url: request.url(), method: request.method(), resourceType: request.resourceType(), pnaPreflight: pnaHeader === 'true', headers });
            }
        } catch (e) {
            // ignore parse errors
        }
    });

    page.on('requestfailed', (r) => {
        try {
            const url = new URL(r.url());
            if (isPrivateHostname(url.hostname)) {
                privateRequests.push({ url: r.url(), method: r.method(), failure: r.failure() });
            }
        } catch (e) {}
    });

    // CDP capture (may not be available in some browser channels)
    try {
        const client = await page.context().newCDPSession(page);
        await client.send('Network.enable');
        client.on('Network.requestWillBeSent', (params) => {
            try {
                const url = params.request.url;
                const hostname = new URL(url).hostname;
                const headers = params.request.headers || {};
                const pna = headers['access-control-request-private-network'] === 'true' || headers['Access-Control-Request-Private-Network'] === 'true';
                if (isPrivateHostname(hostname) || pna) {
                    cdpPrivateRequests.push({ url, method: params.request.method, initiator: params.initiator?.type, pnaPreflight: pna, headers });
                }
            } catch (e) {}
        });
    } catch (e) {
        // CDP not available in this context; continue with high-level capture
    }

    await page.goto('http://demo.localhost:5173/'); // Per README test data
    await page.waitForLoadState('networkidle');

    // Report findings for easier debugging
    if (privateRequests.length > 0 || cdpPrivateRequests.length > 0 || consoleMessages.length > 0) {
        if (consoleMessages.length) {
            console.log('Console messages:');
            consoleMessages.forEach((m) => console.log(m));
        }
        if (privateRequests.length) {
            console.error('Detected private/local requests or PNA preflights (high-level):');
            for (const r of privateRequests) console.error(JSON.stringify(r, null, 2));
        }
        if (cdpPrivateRequests.length) {
            console.error('Detected private/local requests or PNA preflights (CDP):');
            for (const r of cdpPrivateRequests) console.error(JSON.stringify(r, null, 2));
        }
    }

    const total = privateRequests.length + cdpPrivateRequests.length;
    if (total > 0) {
        console.error(`Private-network test detected ${total} items; see logs above.`);
    } else {
        console.log('Private-network test: no private/local requests or PNA preflights detected.');
    }
    // This test is diagnostic by default; it logs issues but does not fail the run.
});
