#!/usr/bin/env python3
"""E2E final: simula clique de ad Google, chega na LP do cliente com UTM, clica WhatsApp, valida evento."""
import asyncio, json
from playwright.async_api import async_playwright

AD_URL = "https://ribeiros.drivetour.erdrones.com.br/?utm_source=google&utm_medium=cpc&utm_campaign=B-destino-algarve&utm_content=algarve-tours&gclid=TEST_E2E_MIA"

async def run():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        ctx = await 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")
        page = await ctx.new_page()
        tracking_reqs = []
        page.on("request", lambda req: tracking_reqs.append(req.url) if any(d in req.url for d in ["googletagmanager","google-analytics","analytics.google","stats.g.doubleclick"]) else None)
        await page.route("**/wa.me/**", lambda route: route.abort())
        resp = await page.goto(AD_URL, wait_until="networkidle", timeout=30000)
        final_url = page.url
        title = await page.title()

        btn = page.locator("a[href*='wa.me']").first
        await btn.scroll_into_view_if_needed(timeout=5000)
        await btn.click(force=True, no_wait_after=True)
        await page.wait_for_timeout(2000)

        dl = await page.evaluate("() => (window.dataLayer || []).slice()")
        wa_evts = [e for e in dl if isinstance(e, dict) and e.get("event") == "whatsapp_click"]

        # Screenshot final
        await page.screenshot(path="/tmp/e2e_ribeiros_mobile.png", full_page=False)

        result = {
            "ad_click_url": AD_URL,
            "landed_url": final_url,
            "landed_status": resp.status,
            "page_title": title,
            "utm_preserved": "utm_source=google" in final_url and "gclid=TEST_E2E_MIA" in final_url,
            "gtm_container_request": any("gtm.js?id=GTM-W785CPB6" in u for u in tracking_reqs),
            "google_tracking_requests_count": len(tracking_reqs),
            "whatsapp_click_events": len(wa_evts),
            "sample_whatsapp_event": wa_evts[0] if wa_evts else None,
            "domain_is_client": "erdrones.com.br" in final_url and "agentesclimb.us" not in final_url,
        }
        print(json.dumps(result, indent=2, ensure_ascii=False))
        await browser.close()

asyncio.run(run())
