"""
Targeted Playwright session for Surebet247 — waits for football events to load.
"""
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', '')
            # Capture everything from sport-iframe domain
            if 'sport-iframe' in url and response.status == 200:
                try:
                    # Try to get JSON
                    if 'json' in ct:
                        body = await response.json()
                    else:
                        body = await response.text()
                    req = response.request
                    req_headers = await req.all_headers()
                    captured.append({
                        'url': url,
                        'ct': ct,
                        'req_headers': dict(req_headers),
                        'body': body,
                    })
                    print(f'[{response.status}] {url[:100]}')
                except Exception as e:
                    print(f'  parse err: {e} {url[:80]}')

        page.on('response', handle_response)

        # Load homepage first
        print('→ Loading homepage...')
        await page.goto('https://www.surebet247.com', wait_until='domcontentloaded', timeout=30000)
        await asyncio.sleep(5)

        # Navigate directly to football
        print('→ Loading football page...')
        await page.goto('https://www.surebet247.com/sport/football', wait_until='domcontentloaded', timeout=30000)
        await asyncio.sleep(6)

        # Scroll to trigger event loading
        print('→ Scrolling...')
        for _ in range(8):
            await page.mouse.wheel(0, 500)
            await asyncio.sleep(0.8)

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

    print(f'\n{"="*70}')
    print(f'Total captured from sport-iframe: {len(captured)}')
    print()

    # Show all unique paths
    paths = sorted(set(r['url'].split('sport-iframe.serhjs.xyz')[1].split('?')[0] for r in captured))
    print('Unique API paths:')
    for p in paths:
        print(f'  {p}')

    print()
    print('=== DETAILED INSPECTION ===')
    for r in captured:
        url = r['url']
        path = url.split('sport-iframe.serhjs.xyz')[1]
        body = r['body']
        body_str = json.dumps(body) if not isinstance(body, str) else body

        # Only show ones with actual match/event data
        if any(kw in body_str[:5000] for kw in ['"name"', 'competitors', 'markets', 'selections', 'odds', 'price']):
            custom = {k: v for k, v in r['req_headers'].items()
                      if k.startswith('x-') or k == 'authorization'}
            print(f'\nPATH: {path[:100]}')
            print(f'Auth headers: {custom}')
            print(f'Response (2000 chars):')
            print(body_str[:2000])
            print('-' * 70)


asyncio.run(main())
