"""Phase 3: probe fixtureList and market structure."""
import json, time
from playwright.sync_api import sync_playwright

GQL_URL = 'https://stake.com/_api/graphql'

SPORTS = {
    'soccer':     '5b4b60b9-ed95-41e7-97e3-f33aa172cf12',
    'tennis':     '8c7aea57-e9b1-414f-a095-206740716b4f',
}

def gql(page, op, query, variables=None):
    body = {'operationName': op, 'query': query, 'variables': variables or {}}
    result = page.evaluate('''async ({url, body}) => {
        const r = await fetch(url, {
            method: 'POST', credentials: 'include',
            headers: {'Content-Type': 'application/json', 'Accept': 'application/json'},
            body: JSON.stringify(body),
        });
        return {status: r.status, body: await r.text()};
    }''', {'url': GQL_URL, 'body': body})
    try:
        return result['status'], json.loads(result['body'])
    except Exception:
        return result['status'], result['body']

def run():
    with sync_playwright() as pw:
        browser = pw.chromium.launch(
            headless=False,
            executable_path='/usr/bin/google-chrome-stable',
            args=['--no-sandbox', '--disable-blink-features=AutomationControlled'],
        )
        ctx = browser.new_context(locale='en-US',
            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')
        page = ctx.new_page()

        print("[1] Loading stake.com/sports/soccer...")
        try:
            page.goto('https://stake.com/sports/soccer', timeout=90_000, wait_until='domcontentloaded')
        except Exception as e:
            print(f"  warn: {e}")
        time.sleep(8)

        # First get full sport list including basketball
        print("\n[2] Full sportList...")
        st, data = gql(page, 'SportList', 'query SportList { sportList { id name slug extId } }')
        if 'data' in data:
            for sp in data['data']['sportList']:
                print(f"  {sp['name']:30} slug={sp['slug']:25} extId={sp['extId']}")
                if 'basketball' in sp['slug'].lower() or 'basket' in sp['name'].lower():
                    SPORTS['basketball'] = sp['id']

        # Probe fixtureList at top level
        print("\n[3] Top-level fixtureList probe...")
        for q_str, label in [
            ('query FL { fixtureList(limit: 3) { id name startTime } }', 'no filter'),
            ('query FL($s: String!) { fixtureList(sportSlug: $s, limit: 3) { id name startTime } }', 'sportSlug'),
            ('query FL($id: String!) { fixtureList(sportId: $id, limit: 3) { id name startTime } }', 'sportId'),
            ('query FL { fixtureList(status: UPCOMING, limit: 3) { id name startTime } }', 'status UPCOMING'),
        ]:
            st, data = gql(page, 'FL', q_str, {'s': 'soccer', 'id': SPORTS.get('soccer','')})
            if 'errors' in data:
                err = data['errors'][0]['message'][:120]
                print(f"  [{label}] status={st} err={err}")
            else:
                items = data.get('data', {}).get('fixtureList', [])
                print(f"  [{label}] status={st} items={len(items)} first={items[0] if items else 'none'}")

        # Probe sport(sportId=uuid).fixtureList
        print("\n[4] sport(sportId=uuid).fixtureList...")
        soccer_id = SPORTS.get('soccer', '')
        for q_str, label in [
            ('''query SF($id: String!) { sport(sportId: $id) { id name fixtureList(limit: 3) { id name startTime } } }''', 'sportId uuid no status'),
            ('''query SF($id: String!) { sport(sportId: $id) { id name fixtureList(status: UPCOMING, limit: 3) { id name startTime } } }''', 'sportId uuid UPCOMING'),
            ('''query SF($s: String!) { sport(slug: $s) { id name fixtureList(limit: 3) { id name startTime } } }''', 'slug'),
        ]:
            st, data = gql(page, 'SF', q_str, {'id': soccer_id, 's': 'soccer'})
            if 'errors' in data:
                err = data['errors'][0]['message'][:120]
                print(f"  [{label}] status={st} err={err}")
            elif 'data' in data and data['data'].get('sport'):
                sp = data['data']['sport']
                fl = sp.get('fixtureList', [])
                print(f"  [{label}] status={st} sport={sp.get('name')} fixtures={len(fl)}")
                for f in fl[:2]:
                    print(f"    {f}")

        # Probe sportByExtId with fixtureList
        print("\n[5] sportByExtId(extId=sr:sport:1).fixtureList...")
        st, data = gql(page, 'SBE', '''query SBE($extId: String!) {
            sportByExtId(extId: $extId) {
                id name
                fixtureList(limit: 5) { id name startTime status }
            }
        }''', {'extId': 'sr:sport:1'})
        if 'errors' in data:
            for e in data['errors']:
                print(f"  err: {e['message'][:150]}")
        elif 'data' in data:
            sp = data['data'].get('sportByExtId') or {}
            fl = sp.get('fixtureList', [])
            print(f"  sport={sp.get('name')} fixtures={len(fl)}")
            for f in fl[:3]:
                print(f"  {f}")

        browser.close()

if __name__ == '__main__':
    run()
