// Re-verifica SOLO los registros con status -1 (artefactos de carga), secuencial + reintentos.
const { chromium } = require('playwright');
const fs=require('fs'), path=require('path');
const DIR=__dirname, F=path.join(DIR,'report.jsonl');
const recs=fs.readFileSync(F,'utf8').split('\n').filter(l=>l.trim()).map(l=>JSON.parse(l));
const bad=recs.filter(r=>r.status===-1);
console.log(`a re-verificar: ${bad.length}`);
const langPrefix=(url)=>{const m=url.match(/\/fea\/(es|en|fr|it|pt)\//);if(m)return m[1];if(/\/fea\//.test(url))return 'es';return '';};
(async()=>{
  const b=await chromium.launch({args:['--ignore-certificate-errors']});
  const ctx=await b.newContext({ignoreHTTPSErrors:true,userAgent:'fea-verify-reverify'});
  const page=await ctx.newPage();
  let fixed=0,stillbad=0;
  for(let i=0;i<bad.length;i++){
    const r=bad[i]; let ok=false;
    for(let a=0;a<3 && !ok;a++){
      try{
        const resp=await page.goto(r.url,{waitUntil:'domcontentloaded',timeout:30000});
        r.status=resp?resp.status():0; r.final=page.url(); r.redirected=r.final!==r.url; r.final_lang=langPrefix(r.final);
        const d=await page.evaluate(()=>{const m=document.querySelector('main,.wp-block-post-content,.entry-content,article')||document.body;return{text:(m.innerText||'').replace(/\s+/g,' ').trim().slice(0,1200),htmlLang:document.documentElement.getAttribute('lang')||'',links:[...new Set(Array.from(document.querySelectorAll('a[href]')).map(a=>a.href).filter(h=>/^https?:/.test(h)))]};});
        r.text=d.text;r.htmlLang=d.htmlLang;r.links=d.links;delete r.error; ok=true; fixed++;
      }catch(e){ r.error=String(e).slice(0,120); await page.waitForTimeout(800); }
    }
    if(!ok) stillbad++;
    if((i+1)%100===0) console.log(`  ${i+1}/${bad.length} (recuperadas ${fixed}, aún mal ${stillbad})`);
  }
  await b.close();
  fs.writeFileSync(F, recs.map(r=>JSON.stringify(r)).join('\n')+'\n');
  console.log(`re-verify done: recuperadas ${fixed}, siguen mal ${stillbad}`);
})();
