"""
Testa o disparo das tags Google Ads Conversion no GTM após publish v6.
Abre px3lab.com.br/cloud-photorf/ e:
  1) Captura todas as requests HTTP.
  2) Injeta um dispatchEvent('wpcf7mailsent') pra simular submit.
  3) Simula click num link WhatsApp (api.whatsapp.com).
  4) Confirma se houve chamada pra googleads.g.doubleclick.net / google-analytics.com/g/collect com AW-975014419
"""
from playwright.sync_api import sync_playwright
import re

URL = "https://www.px3lab.com.br/cloud-photorf/"

conv_requests = []
all_ga_ads = []

def is_conversion_ping(url):
    return (
        "googleads.g.doubleclick.net" in url or
        "www.googleadservices.com" in url or
        "google.com/pagead/conversion" in url or
        "google.com/ads/ga-audiences" in url
    )

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    ctx = browser.new_context(viewport={"width":1366,"height":768}, user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/128.0")
    page = ctx.new_page()

    def on_request(req):
        u = req.url
        if is_conversion_ping(u):
            conv_requests.append(u)
        if "googletagmanager.com" in u or "doubleclick" in u or "googleads" in u or "google-analytics" in u:
            all_ga_ads.append(u)

    page.on("request", on_request)
    page.goto(URL, wait_until="networkidle", timeout=60000)
    page.wait_for_timeout(3000)

    # Aceitar cookie se existir
    try:
        for txt in ["Aceitar", "Aceitar todos", "Ok", "Concordo", "Accept"]:
            btn = page.locator(f"button:has-text('{txt}')").first
            if btn.is_visible():
                btn.click()
                page.wait_for_timeout(1000)
                break
    except Exception:
        pass

    # Confirmar que gtm.js do container carregou
    gtm_loaded = page.evaluate("() => !!(window.google_tag_manager && window.google_tag_manager['GTM-N7J3RPB8'])")
    print("GTM-N7J3RPB8 carregado no browser:", gtm_loaded)

    # Snapshot dataLayer antes
    before_dl = page.evaluate("() => (window.dataLayer || []).length")
    print("dataLayer length before:", before_dl)

    # ============ TESTE 1: Simular wpcf7mailsent ============
    print("\n=== TESTE 1: Disparar wpcf7mailsent ===")
    conv_requests.clear()
    page.evaluate("""
        () => {
            const evt = new CustomEvent('wpcf7mailsent', {
                detail: { contactFormId: 999, inputs: [{name:'nome', value:'Teste QA'}] }
            });
            document.dispatchEvent(evt);
        }
    """)
    page.wait_for_timeout(4000)

    # Ver dataLayer
    dl_events = page.evaluate("() => (window.dataLayer || []).map(x => x.event || x[0] || null)")
    print("dataLayer events depois do wpcf7mailsent:", dl_events)
    has_cf7 = any('cf7_lead' == e for e in dl_events)
    print("cf7_lead push detectado:", has_cf7)

    print("Requests Google Ads Conversion durante form:")
    for u in conv_requests:
        print("  ->", u[:200])
    form_hit = any("AW-975014419" in u or "975014419" in u for u in conv_requests)
    print("Conversao formulario detectada (975014419):", form_hit)

    # ============ TESTE 2: Simular click WhatsApp ============
    print("\n=== TESTE 2: Click no WhatsApp (api.whatsapp.com) ===")
    conv_requests.clear()

    # Injeta um link WhatsApp visivel e clica (evita abrir aba real com trusted click)
    page.evaluate("""
        () => {
            let a = document.createElement('a');
            a.id = 'test_wa';
            a.href = 'https://api.whatsapp.com/send?phone=5511992311361&text=Teste';
            a.textContent = 'wa-test';
            a.target = '_blank';
            a.style.position='fixed';a.style.top='10px';a.style.left='10px';a.style.zIndex=99999;
            document.body.appendChild(a);
        }
    """)
    with ctx.expect_page(timeout=15000) as _new:
        page.click("#test_wa")
    page.wait_for_timeout(4000)

    print("Requests Google Ads Conversion durante WhatsApp:")
    for u in conv_requests:
        print("  ->", u[:200])
    wa_hit = any("AW-975014419" in u or "975014419" in u for u in conv_requests)
    print("Conversao WhatsApp detectada (975014419):", wa_hit)

    page.screenshot(path="/opt/mia/workspace/clientes/px3lab/_tracking_test/lp_post_test.png", full_page=False)
    browser.close()

    print("\n=== TODAS as requests Google/Ads capturadas ===")
    for u in all_ga_ads[-30:]:
        print("  ", u[:180])

    print("\n=== RESULTADO FINAL ===")
    print("Form CF7 -> Google Ads:", "OK" if form_hit else "FALHOU")
    print("WhatsApp click -> Google Ads:", "OK" if wa_hit else "FALHOU")
