"""
Playwright network interceptor for Surebet247 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': 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 = response.request
                    req_headers = await req.all_headers()
                    captured.append({
                        'url': url,
                        'method': req.method,
                        'req_headers': {k: v for k, v in req_headers.items()
                                        if k.lower() not in ('cookie',)},
                        'body': body,
                    })
                    print(f'[JSON] {response.status} {req.method} {url}')
                except Exception:
                    pass

        page.on('response', handle_response)

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

        # Try sports/football pages
        for url in [
            'https://www.surebet247.com/sports',
            'https://www.surebet247.com/sport/football',
            'https://www.surebet247.com/#/sport/football',
            'https://www.surebet247.com/betting/football',
        ]:
            try:
                await page.goto(url, wait_until='domcontentloaded', timeout=20000)
                await asyncio.sleep(4)
                print(f'  Loaded: {url}')
            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')

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

    print()

    # Filter for odds/events data
    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']):
            interesting.append(r)

    print(f'Interesting endpoints ({len(interesting)}):')
    for r in interesting:
        custom_hdrs = {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_hdrs}')
        print(f'Response (first 1000 chars):')
        print(json.dumps(r['body'], indent=2)[:1000])
        print('-' * 60)


asyncio.run(main())
