"""Phase 5: probe sportFixture, sportMarket, correct outcome fields, SportTypeEnum values."""
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()

        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)

        # Try SportTypeEnum values
        print("\n[2] SportTypeEnum values...")
        for val in ['SOCCER', 'FOOTBALL', 'SPORT_SOCCER', 'soccer', 'football', 'PREMATCH']:
            st, data = gql(page, 'FL', f'query FL {{ fixtureList(sportType: {val}, limit: 1) {{ id name }} }}')
            if 'errors' in data:
                err = data['errors'][0]['message'][:100]
                print(f"  {val}: err={err}")
            elif 'data' in data:
                print(f"  {val}: OK! items={len(data['data'].get('fixtureList',[]))}")

        # Probe sportFixture query
        print("\n[3] sportFixture query...")
        for q_str, label in [
            ('query { sportFixture(id: "test") { id name } }', 'by id'),
            ('query SF { sportFixture { id name startTime } }', 'no args'),
            ('query SF($id: String!) { sportFixture(fixtureId: $id) { id name startTime } }', 'fixtureId'),
        ]:
            st, data = gql(page, 'SF', q_str, {'id': '5c415b83-164b-49ce-850e-ae9e4d3a7ce6'})
            if 'errors' in data:
                err = data['errors'][0]['message'][:150]
                print(f"  [{label}] err: {err}")
            else:
                print(f"  [{label}] OK: {json.dumps(data.get('data'))[:200]}")

        # SportFixture fields: see what's available (no homeTeam/awayTeam)
        print("\n[4] sport.fixtureList field discovery...")
        st, data = gql(page, 'SFL', '''query SFL($id: String!) {
            sport(sportId: $id) {
                fixtureList(limit: 3) {
                    id name startTime status slug
                    markets { name extId outcomes { name extId odds } }
                }
            }
        }''', {'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"  fixtures: {len(fl)}")
            for f in fl[:2]:
                print(f"\n  --- {f.get('name')} startTime={f.get('startTime')} ---")
                for mkt in (f.get('markets') or [])[:3]:
                    oc_sample = mkt.get('outcomes', [])[:3]
                    print(f"    market: {mkt.get('name')} extId={mkt.get('extId')} outcomes={oc_sample}")

        # Try outcome field names
        print("\n[5] Outcome field names on SportMarketOutcome...")
        for field in ['odds', 'price', 'coefficient', 'value', 'decimalOdds', 'americanOdds']:
            st, data = gql(page, 'SFL', f'''query SFL($id: String!) {{
                sport(sportId: $id) {{ fixtureList(limit: 1) {{ markets {{ outcomes {{ name {field} }} }} }} }}
            }}''', {'id': SOCCER_ID})
            if 'errors' in data:
                err = data['errors'][0]['message'][:100]
                print(f"  '{field}': err={err}")
            elif 'data' in data:
                sp = data['data'].get('sport', {})
                fl = sp.get('fixtureList', [])
                sample = fl[0]['markets'][0]['outcomes'][0] if fl and fl[0].get('markets') else {}
                print(f"  '{field}': OK sample={sample}")

        # Try to get more fixture fields
        print("\n[6] Additional SportFixture fields...")
        for fields_str, label in [
            ('id name startTime competitors { name position }', 'competitors'),
            ('id name startTime participants { name }', 'participants'),
            ('id name startTime teams { name }', 'teams'),
            ('id name startTime category { name }', 'category'),
            ('id name startTime competition { name }', 'competition'),
            ('id name startTime tournament { name }', 'tournament'),
        ]:
            st, data = gql(page, 'SFL', f'''query SFL($id: String!) {{
                sport(sportId: $id) {{ fixtureList(limit: 1) {{ {fields_str} }} }}
            }}''', {'id': SOCCER_ID})
            if 'errors' in data:
                err = data['errors'][0]['message'][:100]
                print(f"  [{label}] err: {err}")
            elif 'data' in data:
                fl = data['data'].get('sport', {}).get('fixtureList', [])
                print(f"  [{label}] OK: {fl[:1]}")

        browser.close()

if __name__ == '__main__':
    run()
