#!/usr/bin/env python3
"""QA da v11.1 da landing passoapasso2.franciscoborrello.com.br - 4 fixes."""
import json
import os
from playwright.sync_api import sync_playwright

BASE = "https://passoapasso2.franciscoborrello.com.br"
SHOTS = "/opt/mia/workspace/clientes/borrello/auditorias/passoapasso_v11_2026-09-28/v11.1/_shots"
os.makedirs(SHOTS, exist_ok=True)

report = {"tests": [], "screenshots": []}


def check(name, cond, detail=""):
    status = "PASS" if cond else "FAIL"
    report["tests"].append({"name": name, "status": status, "detail": detail})
    print(f"[{status}] {name} :: {detail}")
    return cond


with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)

    # === TEST 1: URL com todos os params -> propaga pro CTA Hotmart ===
    ctx = browser.new_context(viewport={"width": 1440, "height": 900})
    page = ctx.new_page()
    fbq_calls = []
    page.expose_function("_logFbq", lambda args: fbq_calls.append(args))
    page.add_init_script("""
        window.__fbqArgs = [];
        const origFbq = window.fbq;
        Object.defineProperty(window, 'fbq', {
          configurable: true,
          set(v){ this._realFbq = function(){ window.__fbqArgs.push(Array.from(arguments)); return v.apply(this, arguments); }; },
          get(){ return this._realFbq || function(){ window.__fbqArgs.push(Array.from(arguments)); }; }
        });
    """)
    url_full = f"{BASE}/?src=ads0826&utm_campaign=passoapasso_082026&utm_source=fb&utm_medium=paidsocial&fbclid=TESTFIX"
    page.goto(url_full, wait_until="domcontentloaded")
    page.wait_for_timeout(800)

    hotmart_hrefs = page.eval_on_selector_all(
        'a[href*="pay.hotmart.com"]',
        "els => els.map(a => a.href)"
    )
    print("Hotmart hrefs after full-query load:", hotmart_hrefs)
    href = hotmart_hrefs[0] if hotmart_hrefs else ""

    check("hotmart_href_exists", bool(href), href[:120])
    check("propagates_src", "src=ads0826" in href, f"has 'src=ads0826'? {'src=ads0826' in href}")
    check("propagates_utm_campaign", "utm_campaign=passoapasso_082026" in href, "")
    check("propagates_utm_source", "utm_source=fb" in href, "")
    check("propagates_utm_medium", "utm_medium=paidsocial" in href, "")
    check("propagates_fbclid", "fbclid=TESTFIX" in href, "")

    # placeholder GA4 removido
    html_content = page.content()
    check("ga4_placeholder_removed", "{{GA4_ID}}" not in html_content, "placeholder ausente")
    check("ga4_real_id_present", "G-145240655" in html_content, "G-145240655 no HTML")

    # Screenshot desktop top
    page.set_viewport_size({"width": 1440, "height": 900})
    page.screenshot(path=f"{SHOTS}/desktop_1440_top.png", full_page=False)
    report["screenshots"].append(f"{SHOTS}/desktop_1440_top.png")

    ctx.close()

    # === TEST 2: URL SEM query -> fallback ads0826 ===
    ctx = browser.new_context(viewport={"width": 1440, "height": 900})
    page = ctx.new_page()
    page.goto(f"{BASE}/", wait_until="domcontentloaded")
    page.wait_for_timeout(600)
    hotmart_hrefs = page.eval_on_selector_all(
        'a[href*="pay.hotmart.com"]',
        "els => els.map(a => a.href)"
    )
    href2 = hotmart_hrefs[0] if hotmart_hrefs else ""
    print("Hotmart href sem query:", href2)
    check("fallback_src_ads0826", "src=ads0826" in href2, href2[:150])
    check("no_utm_when_absent", "utm_campaign" not in href2, "sem utm quando URL vazia")
    ctx.close()

    # === TEST 3: URL com src=ads0926 (novo criativo) -> propaga src=ads0926 ===
    ctx = browser.new_context(viewport={"width": 1440, "height": 900})
    page = ctx.new_page()
    page.goto(f"{BASE}/?src=ads0926", wait_until="domcontentloaded")
    page.wait_for_timeout(600)
    hotmart_hrefs = page.eval_on_selector_all(
        'a[href*="pay.hotmart.com"]',
        "els => els.map(a => a.href)"
    )
    href3 = hotmart_hrefs[0] if hotmart_hrefs else ""
    print("Hotmart href com src=ads0926:", href3)
    check("override_src_ads0926", "src=ads0926" in href3, "src futuro sobrepoe fallback")
    check("no_double_src", href3.count("src=") == 1, f"src count: {href3.count('src=')}")
    ctx.close()

    # === TEST 4: Botao WhatsApp aponta pro wa.me ===
    ctx = browser.new_context(viewport={"width": 1440, "height": 900})
    page = ctx.new_page()
    page.goto(f"{BASE}/", wait_until="domcontentloaded")
    page.wait_for_timeout(600)
    wa_hrefs = page.eval_on_selector_all(
        'a[href*="wa.me"]',
        "els => els.map(a => ({href: a.href, target: a.target, text: a.textContent.trim()}))"
    )
    print("WA links:", wa_hrefs)
    check("wa_link_exists", len(wa_hrefs) >= 1, f"{len(wa_hrefs)} link(s)")
    if wa_hrefs:
        wa = wa_hrefs[0]
        check("wa_number_correct", "5511942361335" in wa["href"], wa["href"][:100])
        check("wa_opens_new_tab", wa.get("target") == "_blank", f"target={wa.get('target')}")
        check("wa_text_correct", "WhatsApp" in wa["text"], wa["text"])

    # Screenshot da secao com o botao WhatsApp visivel
    page.locator('a[href*="wa.me"]').first.scroll_into_view_if_needed()
    page.wait_for_timeout(400)
    page.screenshot(path=f"{SHOTS}/desktop_wa_button.png", full_page=False)
    report["screenshots"].append(f"{SHOTS}/desktop_wa_button.png")
    ctx.close()

    # === TEST 5: fbq InitiateCheckout so no CTA Hotmart, nao nas ancoras ===
    ctx = browser.new_context(viewport={"width": 1440, "height": 900})
    page = ctx.new_page()
    # Stub fbq pra capturar chamadas
    page.add_init_script("""
        window.__fbqCalls = [];
        window.fbq = function(){ window.__fbqCalls.push(Array.from(arguments)); };
    """)
    page.goto(f"{BASE}/", wait_until="domcontentloaded")
    page.wait_for_timeout(600)

    # Simula click em cada ancora #oferta (sem seguir link) e checa se disparou InitiateCheckout
    anchor_ic_counts = page.evaluate("""
        () => {
          const results = [];
          document.querySelectorAll('a[href="#oferta"]').forEach((a, i) => {
            const before = window.__fbqCalls.filter(c => c[0]==='track' && c[1]==='InitiateCheckout').length;
            // dispara handler onclick manualmente sem navegacao
            try { a.onclick && a.onclick(new Event('click')); } catch(e){}
            const after = window.__fbqCalls.filter(c => c[0]==='track' && c[1]==='InitiateCheckout').length;
            results.push({index: i, text: a.textContent.trim().slice(0,40), href: a.getAttribute('href'), ic_fired: after - before});
          });
          return results;
        }
    """)
    print("Anchor #oferta results:", json.dumps(anchor_ic_counts, indent=2, ensure_ascii=False))
    anchors_firing_ic = sum(1 for r in anchor_ic_counts if r["ic_fired"] > 0)
    check("anchors_dont_fire_ic", anchors_firing_ic == 0,
          f"{anchors_firing_ic} ancoras disparando InitiateCheckout (esperado 0)")

    # Simula click no CTA Hotmart (sem navegacao)
    hotmart_ic = page.evaluate("""
        () => {
          const before = window.__fbqCalls.filter(c => c[0]==='track' && c[1]==='InitiateCheckout').length;
          const a = document.querySelector('a[href*="pay.hotmart.com"]');
          if(!a) return {found: false, fired: 0};
          try { a.onclick && a.onclick(new Event('click')); } catch(e){}
          const after = window.__fbqCalls.filter(c => c[0]==='track' && c[1]==='InitiateCheckout').length;
          return {found: true, fired: after - before, href: a.href};
        }
    """)
    print("Hotmart CTA:", hotmart_ic)
    check("hotmart_fires_ic", hotmart_ic.get("fired", 0) == 1,
          f"CTA Hotmart disparou {hotmart_ic.get('fired',0)} IC (esperado 1)")
    ctx.close()

    # === Screenshots mobile 375 ===
    ctx = browser.new_context(viewport={"width": 375, "height": 812},
                              user_agent="Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X)")
    page = ctx.new_page()
    page.goto(f"{BASE}/?src=ads0826&utm_campaign=test", wait_until="domcontentloaded")
    page.wait_for_timeout(800)
    page.screenshot(path=f"{SHOTS}/mobile_375_top.png", full_page=False)
    report["screenshots"].append(f"{SHOTS}/mobile_375_top.png")
    ctx.close()

    browser.close()

# Summary
passed = sum(1 for t in report["tests"] if t["status"] == "PASS")
failed = sum(1 for t in report["tests"] if t["status"] == "FAIL")
report["summary"] = {"total": len(report["tests"]), "passed": passed, "failed": failed}

with open("/opt/mia/workspace/clientes/borrello/auditorias/passoapasso_v11_2026-09-28/v11.1/qa_report.json", "w") as f:
    json.dump(report, f, indent=2, ensure_ascii=False)

print(f"\n=== SUMMARY: {passed} passed, {failed} failed of {len(report['tests'])} ===")
exit(0 if failed == 0 else 1)
