"""
Playwright network interceptor for Betway Nigeria API discovery.
"""
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': 900},
        )
        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 = response.request
                    req_headers = await req.all_headers()
                    captured.append({
                        'url': url,
                        'method': req.method,
                        'req_headers': dict(req_headers),
                        'body': body,
                    })
                    print(f'[{response.status}] {req.method} {url}')
                except Exception:
                    pass

        page.on('response', handle_response)

        print('→ Loading betway.com.ng ...')
        for start_url in [
            'https://www.betway.com.ng',
            'https://betway.com.ng',
        ]:
            try:
                await page.goto(start_url, wait_until='domcontentloaded', timeout=30000)
                await asyncio.sleep(4)
                print(f'  Loaded: {start_url}')
                break
            except Exception as e:
                print(f'  Failed {start_url}: {e}')

        for nav_url in [
            'https://www.betway.com.ng/sport/football',
            'https://www.betway.com.ng/sports/football',
            'https://www.betway.com.ng/sport',
            'https://www.betway.com.ng/#sport/football',
        ]:
            try:
                await page.goto(nav_url, wait_until='domcontentloaded', timeout=20000)
                await asyncio.sleep(5)
                print(f'  Loaded: {nav_url}')
            except Exception as e:
                print(f'  Failed {nav_url}: {e}')

        for _ in range(8):
            await page.mouse.wheel(0, 600)
            await asyncio.sleep(0.8)

        await asyncio.sleep(3)
        await browser.close()

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

    print('All captured URLs:')
    for r in captured:
        print(f'  [{r["method"]}] {r["url"]}')

    print()

    interesting = []
    for r in captured:
        body_str = json.dumps(r['body'])
        if any(kw in body_str.lower() for kw in [
            'home', 'away', 'odds', 'match', 'event', 'sport',
            'football', 'price', 'market', 'selection', 'team',
        ]):
            interesting.append(r)

    print(f'Interesting endpoints ({len(interesting)}):')
    for r in interesting:
        custom = {k: v for k, v in r['req_headers'].items()
                  if k.lower() 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',
                      ':authority', ':method', ':path', ':scheme', 'priority',
                  )}
        print(f'\nURL: {r["url"]}')
        print(f'Custom headers: {custom}')
        print(f'Response (first 1200 chars):')
        print(json.dumps(r['body'], indent=2)[:1200])
        print('-' * 70)


asyncio.run(main())
