#!/usr/bin/env python3
"""Auditoria fim-a-fim landing v11 + checkout Hotmart."""
import json, os, time, sys
from playwright.sync_api import sync_playwright

OUT = "/opt/mia/workspace/clientes/borrello/auditorias/passoapasso_v11_2026-09-28"
V11 = "https://passoapasso2.franciscoborrello.com.br/?src=ads0826&utm_campaign=passoapasso_082026&utm_source=fb&utm_medium=paidsocial&fbclid=TEST123"
V10 = "https://passoapasso.franciscoborrello.com.br/?src=ads0826&utm_campaign=passoapasso_082026&fbclid=TEST123"

VIEWPORTS = [
    ("mobile_375",  375,  812),
    ("tablet_768",  768,  1024),
    ("laptop_1366", 1366, 800),
    ("desktop_1440",1440, 900),
]

report = {"v11": {}, "v10": {}, "hotmart": {}, "network": {"pixel_calls": [], "hotmart_calls": [], "console_errors": []}}

def collect_console(page, key):
    page.on("console", lambda msg: report["network"]["console_errors"].append({"page":key,"type":msg.type,"text":msg.text[:300]}) if msg.type in ("error","warning") else None)
    page.on("pageerror", lambda err: report["network"]["console_errors"].append({"page":key,"type":"pageerror","text":str(err)[:300]}))

def collect_requests(page, key):
    def on_req(req):
        url = req.url
        if "facebook.com/tr" in url or "connect.facebook.net" in url:
            report["network"]["pixel_calls"].append({"page":key,"url":url[:400],"method":req.method})
        if "hotmart" in url:
            report["network"]["hotmart_calls"].append({"page":key,"url":url[:400],"method":req.method})
    page.on("request", on_req)

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True, args=["--no-sandbox"])

    # === V11 — quatro viewports + auditoria de CTAs ===
    for name, w, h in VIEWPORTS:
        ctx = browser.new_context(viewport={"width":w,"height":h}, user_agent="Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 Mobile/15E148 Safari/604.1" if w<500 else None)
        page = ctx.new_page()
        collect_console(page, f"v11_{name}")
        collect_requests(page, f"v11_{name}")
        try:
            page.goto(V11, wait_until="networkidle", timeout=30000)
            time.sleep(2)
            page.screenshot(path=f"{OUT}/shots/v11_{name}_top.png", full_page=False)
            # Extrai todos os CTAs Hotmart e ancoras
            ctas = page.evaluate("""() => {
                const links = Array.from(document.querySelectorAll('a'));
                return links.filter(a=>a.href && (a.href.includes('hotmart')||a.href.includes('#oferta')||a.textContent.match(/quero|garantir|comprar|acesso/i)))
                    .map(a=>({href:a.href, text:a.textContent.trim().slice(0,60), onclick:a.getAttribute('onclick')||'', class:a.className.slice(0,80)}));
            }""")
            report["v11"][name] = {"cta_count": len(ctas), "ctas": ctas[:20]}
        except Exception as e:
            report["v11"][name] = {"error": str(e)}
        ctx.close()

    # === V11 — extrai URL final do CTA principal e simula clique ===
    ctx = browser.new_context(viewport={"width":1366,"height":800})
    page = ctx.new_page()
    collect_console(page, "v11_click")
    collect_requests(page, "v11_click")
    try:
        page.goto(V11, wait_until="networkidle", timeout=30000)
        # Pega o link Hotmart direto
        hot_href = page.evaluate("""() => {
            const a = document.querySelector('a[href*=\"pay.hotmart.com\"]');
            return a ? a.href : null;
        }""")
        report["v11"]["hotmart_href_raw"] = hot_href

        # Simula clique real e captura navegação
        with page.expect_navigation(wait_until="domcontentloaded", timeout=20000) as nav_info:
            page.evaluate("""() => {
                const a = document.querySelector('a[href*=\"pay.hotmart.com\"]');
                a.click();
            }""")
        final_url = page.url
        report["v11"]["hotmart_url_after_click"] = final_url
        page.screenshot(path=f"{OUT}/shots/checkout_desktop.png", full_page=False)
        # analisa params
        from urllib.parse import urlparse, parse_qs
        parsed = urlparse(final_url)
        report["v11"]["checkout_host"] = parsed.netloc
        report["v11"]["checkout_params"] = {k:v[0] for k,v in parse_qs(parsed.query).items()}
    except Exception as e:
        report["v11"]["click_error"] = str(e)
    ctx.close()

    # === V10 ===
    ctx = browser.new_context(viewport={"width":1366,"height":800})
    page = ctx.new_page()
    collect_console(page, "v10")
    try:
        resp = page.goto(V10, wait_until="domcontentloaded", timeout=15000)
        report["v10"]["status"] = resp.status if resp else None
        report["v10"]["final_url"] = page.url
        report["v10"]["title"] = page.title()
        page.screenshot(path=f"{OUT}/shots/v10_desktop.png", full_page=False)
    except Exception as e:
        report["v10"]["error"] = str(e)
    ctx.close()

    # === Hotmart mobile 375 ===
    ctx = browser.new_context(viewport={"width":375,"height":812}, user_agent="Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 Mobile/15E148 Safari/604.1")
    page = ctx.new_page()
    collect_console(page, "checkout_mobile")
    hotmart_url = "https://pay.hotmart.com/H52956404P?off=d64ejplo&checkoutMode=10&src=ads0826&utm_campaign=passoapasso_082026&utm_source=fb&fbclid=TEST123"
    try:
        t0 = time.time()
        page.goto(hotmart_url, wait_until="networkidle", timeout=45000)
        report["hotmart"]["load_time_s"] = round(time.time()-t0, 2)
        report["hotmart"]["final_url"] = page.url
        report["hotmart"]["title"] = page.title()
        time.sleep(3)
        page.screenshot(path=f"{OUT}/shots/checkout_mobile_375.png", full_page=False)
        page.screenshot(path=f"{OUT}/shots/checkout_mobile_full.png", full_page=True)
        # Extrai preço visível
        try:
            price_texts = page.evaluate("""() => {
                const nodes = Array.from(document.querySelectorAll('*'));
                const found = [];
                for (const n of nodes) {
                    const t = (n.innerText||'').trim();
                    if (t && t.length < 100 && /R\\$\\s*\\d+/.test(t) && !found.some(f=>f.includes(t))) found.push(t);
                    if (found.length > 12) break;
                }
                return found;
            }""")
            report["hotmart"]["price_texts"] = price_texts
        except Exception as e:
            report["hotmart"]["price_extract_err"] = str(e)
        # Botão pagamento visível?
        try:
            btn_visible = page.evaluate("""() => {
                const btns = Array.from(document.querySelectorAll('button, [role=button], input[type=submit]'));
                const vh = window.innerHeight;
                const above = btns.filter(b=>{const r=b.getBoundingClientRect();return r.top>=0 && r.top<vh && r.height>0 && (b.innerText||b.value||'').match(/pag|compr|final|conclu/i);});
                return {total_btns: btns.length, above_fold_pay: above.length, first_pay_text: above[0] ? (above[0].innerText||above[0].value||'').slice(0,60) : null};
            }""")
            report["hotmart"]["btn_check"] = btn_visible
        except Exception as e:
            report["hotmart"]["btn_err"] = str(e)
    except Exception as e:
        report["hotmart"]["error"] = str(e)
    ctx.close()

    browser.close()

with open(f"{OUT}/report.json","w") as f:
    json.dump(report, f, ensure_ascii=False, indent=2)

print(json.dumps({k: (v if k!="network" else {"pixel_calls_n":len(v["pixel_calls"]),"hotmart_calls_n":len(v["hotmart_calls"]),"console_errors_n":len(v["console_errors"])}) for k,v in report.items()}, ensure_ascii=False, indent=2)[:4000])
