const jsdom = require('jsdom');
const { JSDOM } = jsdom;
const dom = new JSDOM($html);
const document = dom.window.document;

function extractContext(b){
  var curr = b.parentElement;
  var bestDesc = '';
  var btnText = (b.innerText || b.textContent || '').trim();

  for (var i = 0; i < 15 && curr; i++) {
    var codeEl = curr.querySelector('pre, code, [class*="command"], [class*="terminal"], [class*="code"]');
    if (codeEl && codeEl !== b && !b.contains(codeEl)) {
      var codeText = (codeEl.innerText || codeEl.textContent || '').trim();
      if (codeText.length > 0 && codeText !== btnText) {
        return codeText.substring(0, 500);
      }
    }

    var full = (curr.innerText || curr.textContent || '');
    var btnRawText = (b.textContent || ''); 
    var desc = full.replace(btnRawText, '').trim();
    if (desc.length > 5 && desc !== btnText && bestDesc.length < desc.length) {
       bestDesc = desc;
    }
    
    var cname = curr.className;
    if (typeof cname === 'string' && (cname.includes('message') || cname.includes('step') || cname.includes('markdown'))) {
       break;
    }
    curr = curr.parentElement;
  }
  return bestDesc.substring(0, 500);
}

const btns = document.querySelectorAll('button');
let ran = false;
for(let b of btns) {
    let t = (b.textContent||'').trim();
    if(t === 'Always run' || t === 'Run') {
        const desc = extractContext(b);
        console.log("Found button: " + t);
        console.log("Extracted Description: " + desc);
        ran = true;
    }
}
if(!ran) console.log("No matching button found");
