"""Phase 4: probe match/event structure inside fixtures."""
import json, time
from playwright.sync_api import sync_playwright

GQL_URL = 'https://stake.com/_api/graphql'
SOCCER_ID = '5b4b60b9-ed95-41e7-97e3-f33aa172cf12'

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()

        # Intercept real page GQL calls
        REAL_GQL = []
        def on_req(req):
            if '_api/graphql' in req.url and req.method == 'POST':
                try:
                    b = req.post_data_json
                    REAL_GQL.append({'op': b.get('operationName','?'), 'query': b.get('query',''), 'vars': b.get('variables',{})})
                except Exception:
                    pass
        page.on('request', on_req)

        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(12)

        # Check what real GQL calls the page makes
        sport_calls = [x for x in REAL_GQL if 'sport' in x['op'].lower() or 'fixture' in x['op'].lower() or 'event' in x['op'].lower() or 'match' in x['op'].lower()]
        print(f"  Real page GQL ops: {[x['op'] for x in REAL_GQL]}")
        print(f"  Sport-related: {[x['op'] for x in sport_calls]}")
        if sport_calls:
            for c in sport_calls[:3]:
                print(f"  op={c['op']} vars={c['vars']} query_snippet={c['query'][:200]}")

        # Probe 1: top-level fixtureList with sportType
        print("\n[2] fixtureList(sportType='soccer')...")
        st, data = gql(page, 'FL', 'query FL { fixtureList(sportType: "soccer", limit: 5) { id name startTime } }')
        if 'errors' in data:
            print(f"  err: {data['errors'][0]['message'][:150]}")
        elif 'data' in data:
            items = data['data'].get('fixtureList', [])
            print(f"  items={len(items)}")
            for it in items[:3]:
                print(f"  {it}")

        # Probe 2: query a fixture by ID and look for matches/events nested
        fixture_id = '5c415b83-164b-49ce-850e-ae9e4d3a7ce6'  # Premier League 25/26
        print(f"\n[3] fixture(id='{fixture_id}') structure...")
        for q_str, label in [
            ('''query F($id: String!) { fixture(id: $id) { id name startTime homeTeam { name } awayTeam { name } markets { name outcomes { name price } } } }''', 'with markets'),
            ('''query F($id: String!) { fixture(id: $id) { id name startTime status slug homeTeamId awayTeamId } }''', 'basic fields'),
            ('''query F($id: String!) { fixture(id: $id) { id name matches { id name startTime homeTeam { name } awayTeam { name } } } }''', 'with matches'),
            ('''query F($id: String!) { fixture(id: $id) { id name events { id name startTime homeTeam { name } awayTeam { name } } } }''', 'with events'),
        ]:
            st, data = gql(page, 'F', q_str, {'id': fixture_id})
            if 'errors' in data:
                print(f"  [{label}] err: {data['errors'][0]['message'][:150]}")
            elif 'data' in data:
                f = data['data'].get('fixture')
                print(f"  [{label}] data: {json.dumps(f)[:300]}")

        # Probe 3: use sport(sportId).fixtureList with more fields
        print(f"\n[4] sport(sportId).fixtureList - full fixture structure...")
        st, data = gql(page, 'SFL', '''query SFL($id: String!) {
            sport(sportId: $id) {
                id name
                fixtureList(limit: 3) {
                    id name startTime status slug
                    homeTeam { id name }
                    awayTeam { id name }
                    markets { name outcomes { name price } }
                }
            }
        }''', {'id': SOCCER_ID})
        if 'errors' in data:
            for e in data['errors']:
                print(f"  err: {e['message'][:150]}")
        elif 'data' in data:
            sp = data['data'].get('sport', {})
            fl = sp.get('fixtureList', [])
            print(f"  soccer fixtures: {len(fl)}")
            for f in fl[:2]:
                print(f"\n  --- {f.get('name')} ---")
                print(json.dumps(f, indent=2)[:800])

        # Probe 4: check if there's a matchList or individual event query
        print("\n[5] Probing alternative event queries...")
        for q_str, label in [
            ('query { matchList(limit: 3) { id name } }', 'matchList'),
            ('query { eventList(limit: 3) { id name } }', 'eventList'),
            ('query { sportMatchList(limit: 3) { id name } }', 'sportMatchList'),
            ('query { upcomingFixtures(limit: 3) { id name } }', 'upcomingFixtures'),
            ('query { prematchList(limit: 3) { id name } }', 'prematchList'),
        ]:
            st, data = gql(page, 'Q', q_str)
            if 'errors' in data:
                err = data['errors'][0]['message'][:100]
                print(f"  [{label}] err: {err}")
            else:
                items = list(data.get('data',{}).values())
                print(f"  [{label}] status={st} data: {items[:1]}")

        # Save all real GQL calls
        with open('/home/cyborg/Desktop/claude/arb_bot/tools/stake_real_gql.json', 'w') as f:
            json.dump(REAL_GQL, f, indent=2, default=str)
        print(f"\nSaved {len(REAL_GQL)} real GQL calls to stake_real_gql.json")
        browser.close()

if __name__ == '__main__':
    run()
