from pathlib import Path
p = Path('/var/www/html/_inc/whatsapp_v2/admin/receipts.php')
if not p.exists():
    print('receipts.php no existe')
    raise SystemExit(0)

s = p.read_text()

if 'function analyzeReceipt(' not in s:
    marker = 'async function downloadReceipt'
    func = "async function analyzeReceipt(id){try{const data=await jfetch(api+'?action=analyze_receipt',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'receipt_id='+encodeURIComponent(id)});alert('Análisis IA completado');await openReceipt(id);loadReceipts();}catch(e){alert(e.message);}}\n"
    if marker in s:
        s = s.replace(marker, func + marker, 1)

if 'Analizar con IA' not in s:
    s = s.replace(
        'box.innerHTML=`<img src="${esc(url)}" alt="Comprobante">`;',
        'box.innerHTML=`<div style="width:100%;height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px"><img src="${esc(url)}" alt="Comprobante"><button class="btn" onclick="analyzeReceipt(${Number(r.id)})">Analizar con IA</button></div>`;',
        1
    )
    s = s.replace(
        'box.innerHTML=`<iframe src="${esc(url)}"></iframe>`;',
        'box.innerHTML=`<div style="width:100%;height:100%;display:flex;flex-direction:column"><iframe src="${esc(url)}" style="flex:1"></iframe><button class="btn" onclick="analyzeReceipt(${Number(r.id)})">Analizar con IA</button></div>`;',
        1
    )

p.write_text(s)
print('OK receipts UI parcheado')
