"""
Playwright network interceptor for NairaBet API discovery.
Navigates to the football section and captures all JSON API calls.
"""
import json
import asyncio
from playwright.async_api import async_playwright


async def main():
    captured = []

    async with async_playwright() as p:
        browser = await p.chromium.launch(
            headless=True,
            args=[
                '--no-sandbox',
                '--disable-blink-features=AutomationControlled',
            ]
        )
        ctx = await browser.new_context(
            user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            viewport={'width': 1280, 'height': 800},
        )
        page = await ctx.new_page()

        async def handle_response(response):
            url = response.url
            ct = response.headers.get('content-type', '')
            if 'json' in ct and response.status == 200:
                try:
                    body = await response.json()
                    req_headers = await response.request.all_headers()
                    captured.append({
                        'url': url,
                        'status': response.status,
                        'req_headers': {k: v for k, v in req_headers.items()
                                        if k.lower() not in ('cookie', 'authorization')},
                        'body_preview': body,
                    })
                    print(f"[JSON] {response.status} {url}")
                except Exception:
                    pass

        page.on('response', handle_response)

        print("→ Loading nairabet.com ...")
        try:
            await page.goto('https://www.nairabet.com', wait_until='domcontentloaded', timeout=30000)
        except Exception as e:
            print(f"Homepage load error: {e}")

        await asyncio.sleep(3)

        print("→ Navigating to football/sports ...")
        for url in [
            'https://www.nairabet.com/sports',
            'https://www.nairabet.com/sport/football',
            'https://www.nairabet.com/#/sport/football',
        ]:
            try:
                await page.goto(url, wait_until='domcontentloaded', timeout=20000)
                await asyncio.sleep(4)
                print(f"  Loaded: {url}")
                break
            except Exception as e:
                print(f"  Failed {url}: {e}")

        # Scroll to trigger lazy loads
        for _ in range(5):
            await page.mouse.wheel(0, 800)
            await asyncio.sleep(1)

        await browser.close()

    print(f"\n{'='*60}")
    print(f"Captured {len(captured)} JSON responses\n")

    # Filter for likely odds/events endpoints (has list/array data)
    interesting = []
    for r in captured:
        body = r['body_preview']
        body_str = json.dumps(body)
        # Look for responses that contain team names, odds, or event data
        if any(kw in body_str.lower() for kw in ['home', 'away', 'odds', 'match', 'event', 'sport', 'football']):
            interesting.append(r)

    print(f"Interesting endpoints ({len(interesting)}):\n")
    for r in interesting:
        print(f"URL: {r['url']}")
        print(f"Custom headers: { {k:v for k,v in r['req_headers'].items() if k not in ('accept','user-agent','accept-encoding','accept-language','cache-control','pragma','sec-fetch-dest','sec-fetch-mode','sec-fetch-site','sec-ch-ua','sec-ch-ua-mobile','sec-ch-ua-platform','connection','host')} }")
        print(f"Response preview (first 800 chars):")
        print(json.dumps(r['body_preview'], indent=2)[:800])
        print("-" * 60)

    if not interesting:
        print("No interesting endpoints found.")
        print("\nAll captured URLs:")
        for r in captured:
            print(f"  {r['url']}")


asyncio.run(main())
