const fs = require('fs');
const { JSDOM } = require("jsdom");

try {
    const observerModule = require("./extension/out/observer-script.js");

    const dumpRaw = fs.readFileSync('C:\\Users\\Variet-Worker\\.gemini\\antigravity\\bridge\\dump_html.json', 'utf8');
    const parseData = JSON.parse(dumpRaw);
    let htmlStr = parseData.html;

    // Inject fake port discovery node so it passes discoverPort()
    htmlStr += `<div aria-label="Gravity Bridge Control port:1234"></div>`;

    const dom = new JSDOM(htmlStr, { url: "http://localhost/", runScripts: "dangerously" });
    const window = dom.window;
    const document = window.document;

    let testResults = [];
    
    // Mock fetch for the observer
    window.fetch = async (url, options) => {
        if (url.includes('/ping')) {
            return { text: async () => 'pong' };
        }
        if (url.includes('/pending') && options?.method === 'POST') {
            const body = JSON.parse(options.body);
            testResults.push("✅ POST /pending intercepted! Payload:");
            testResults.push(JSON.stringify(body, null, 2));
            return { json: async () => ({ok: true, request_id: body.request_id}) };
        }
        return { json: async () => ({}) };
    };
    
    // Fallback overrides
    window.console.log = (m) => testResults.push(`[Script Log] ${m}`);
    window.MutationObserver = window.MutationObserver || class { observe(){} };
    window.AbortSignal = { timeout: () => ({}) };

    let scriptStr = observerModule.generateApprovalObserverScript(1234);
    // Brutally bypass discoverPort block and force initialization
    scriptStr = scriptStr.replace(/discoverPort\(function\(port\)\{[\s\S]*?\}\);/, "BASE='http://127.0.0.1:1234';_ready=true;startObserver();");
    scriptStr = scriptStr.replace("function scan(){", "function scan(){ log('scan() STAGE 1'); log('buttons in DOM: ' + document.querySelectorAll('button').length);");
    scriptStr = scriptStr.replace("_obs=true;", "_obs=true; log('Forcing scan'); scan();");

    // Run script inside JSDOM
    const scriptEl = document.createElement("script");
    scriptEl.textContent = scriptStr;
    document.body.appendChild(scriptEl);

    // Wait 3 seconds for discoverPort -> ping -> startObserver -> scheduleScan to execute
    setTimeout(() => {
        console.log("=== TEST RESULTS ===");
        console.log(testResults.join("\n"));
        if (!testResults.some(l => l.includes('POST /pending intercepted'))) {
            console.error("❌ FAILED: No POST to /pending was made. The DOM scan failed to find the dummy button or extract context.");
            process.exit(1);
        } else {
            console.log("✅ SUCCESS: The DOM extraction is functioning properly.");
            process.exit(0);
        }
    }, 3000);

} catch (e) {
    console.error("Test Harness Error:", e);
    process.exit(1);
}
