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

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

    const dom = new JSDOM(htmlStr);
    const document = dom.window.document;

    // Direct copy of functions from observer-script.ts
    function findButtonContainer(btn){
        return btn.closest('.p-1')
            || btn.closest('.bg-agent-convo-background')
            || btn.closest('[class*="border-gray-500/10"]')
            || btn.closest('.monaco-list-row')
            || btn.parentElement;
    }

    function cleanButtonText(btn) {
        if (!btn) return '';
        var tr = btn.querySelector('.truncate');
        var txt = (tr ? tr.textContent : btn.textContent) || '';
        return txt.trim().replace(/(Alt|Ctrl|Shift|Meta)\+.*/i,'').trim();
    }

    function extractContext(b){
        var container = findButtonContainer(b);
        if (!container) return "ERROR_NO_CONTAINER";

        var titleSpans = container.querySelectorAll('span[title^="command("]');
        if (titleSpans && titleSpans.length > 0) {
            var t = titleSpans[0].getAttribute('title');
            if (t && t.length > 5) return "METHOD=TITLE_SPAN | " + t.substring(0, 800);
        }
        
        var preEls = container.querySelectorAll('pre');
        if (preEls && preEls.length > 0) {
            var t2 = (preEls[preEls.length-1].textContent || '').trim();
            if (t2.length > 2) return "METHOD=PRE_SPAN | " + t2.substring(0, 800);
        }
        
        var codeText = '';
        var codes = container.querySelectorAll('code, [class*="command"]');
        for(var i=0; i<codes.length; i++) {
            codeText += (codes[i].textContent || '').trim() + ' ';
        }
        if (codeText.length > 2) return "METHOD=CODES | " + codeText.trim().substring(0, 800);

        var fallback = (container.textContent || '').replace(cleanButtonText(b), '').trim();
        return "METHOD=FALLBACK | " + fallback.substring(0, 500);
    }

    // RUN TEST
    const allBtns = document.querySelectorAll('button');
    console.log(`Total buttons found: ${allBtns.length}`);
    
    let tested = 0;
    for(let j=0; j<allBtns.length; j++) {
        let b = allBtns[j];
        let txt = cleanButtonText(b);
        if (txt.length <= 1) continue; // Icon
        
        var PATS = [
            { type: 'command', re: /^(?:Always\s*)?Run\b/i },
            { type: 'permission', re: /^(?:Always\s*)?Allow\b/i },
            { type: 'permission', re: /^(?:Always\s*)?Approve\b/i },
            { type: 'diff_review', re: /^(?:Always\s*)?Accept\b/i }
        ];

        var matchedType=null;
        for(var p=0;p<PATS.length;p++){
            if(PATS[p].re.test(txt)){
                matchedType=PATS[p].type;
                break;
            }
        }

        if (!matchedType) continue;

        console.log(`\n✅ Matched Button: "${txt}" (Type: ${matchedType})`);
        console.log(`   Extracting Context Data...`);
        console.log(`   -> ` + extractContext(b));
        tested++;
    }

    if (tested === 0) {
        console.log("❌ No actionable buttons matched!");
        process.exit(1);
    } else {
        console.log("\n✅ SUCCESS: Context fully extracted via DOM script logic.");
        process.exit(0);
    }
} catch (e) {
    console.error(e);
    process.exit(1);
}
