"""
Stake.com API discovery — intercepts real GQL calls made by the page.
Navigates to stake.com/sports/soccer, waits for CF clearance, 
then captures actual GraphQL requests via network interception.
"""
import json, time, sys
from playwright.sync_api import sync_playwright

GQL_URL = 'https://stake.com/_api/graphql'
INTERCEPTED = []

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 GQL requests
        def on_request(req):
            if '_api/graphql' in req.url and req.method == 'POST':
                try:
                    body = req.post_data_json
                    op = body.get('operationName', '?') if body else '?'
                    print(f"  [REQ] op={op}")
                    INTERCEPTED.append({'op': op, 'body': body, 'headers': dict(req.headers)})
                except Exception:
                    pass

        def on_response(resp):
            if '_api/graphql' in resp.url:
                try:
                    body = resp.json()
                    op = INTERCEPTED[-1]['op'] if INTERCEPTED else '?'
                    INTERCEPTED[-1]['response'] = body
                    print(f"  [RESP] op={op} keys={list(body.get('data', {}).keys()) if 'data' in body else 'error'}")
                except Exception as e:
                    print(f"  [RESP] parse error: {e}")

        page.on('request', on_request)
        page.on('response', on_response)

        # 1. Load home page first to get CF cookies
        print("[1] Loading home page...")
        try:
            page.goto('https://stake.com/', timeout=60_000, wait_until='domcontentloaded')
        except Exception as e:
            print(f"  warn: {e}")
        time.sleep(5)
        print(f"  url: {page.url}")

        # 2. Try to navigate to soccer
        print("[2] Loading 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(15)  # Wait for CF waiting room + page JS
        print(f"  url: {page.url}")
        print(f"  title: {page.title()}")
        print(f"  Intercepted so far: {len(INTERCEPTED)}")

        # 3. Make a GQL request from inside the browser context
        print("[3] Making GQL call via evaluate()...")
        
        # Try common stake.com GraphQL operations
        queries = [
            {
                'operationName': 'SportFixtures',
                'query': '''query SportFixtures($slug: String!) {
                    sport(slug: $slug) {
                        slug name
                        competitions {
                            name slug
                            fixtures(status: UPCOMING) {
                                id slug name startTime
                                homeTeam { name } awayTeam { name }
                                markets { name outcomes { name price } }
                            }
                        }
                    }
                }''',
                'variables': {'slug': 'soccer'}
            },
            {
                'operationName': 'UpcomingEvents',
                'query': '''query UpcomingEvents($sport: String!, $limit: Int) {
                    sportEvents(sport: $sport, status: UPCOMING, limit: $limit) {
                        id name startTime
                        homeTeam { name } awayTeam { name }
                        markets { name outcomes { name price odds } }
                    }
                }''',
                'variables': {'sport': 'soccer', 'limit': 20}
            },
        ]

        for q in queries:
            try:
                result = page.evaluate('''async ({url, body}) => {
                    const r = await fetch(url, {
                        method: 'POST',
                        credentials: 'include',
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json',
                            'x-access-token': '',
                        },
                        body: JSON.stringify(body),
                    });
                    return { status: r.status, body: await r.text() };
                }''', {'url': GQL_URL, 'body': q})
                status = result['status']
                body_text = result['body'][:500]
                print(f"  op={q['operationName']} status={status} body={body_text}")
            except Exception as e:
                print(f"  op={q['operationName']} eval error: {e}")

        # 4. Print any intercepted real GQL calls
        print(f"\n[4] All intercepted GQL calls: {len(INTERCEPTED)}")
        for entry in INTERCEPTED:
            print(f"\n  op={entry['op']}")
            if entry.get('body'):
                print(f"  query: {entry['body'].get('query', '')[:200]}")
                print(f"  vars:  {entry['body'].get('variables', {})}")
            if entry.get('response') and 'data' in entry['response']:
                print(f"  data keys: {list(entry['response']['data'].keys())}")
                print(f"  data sample: {json.dumps(entry['response']['data'])[:400]}")

        # 5. Save raw results
        with open('/home/cyborg/Desktop/claude/arb_bot/tools/stake_raw.json', 'w') as f:
            json.dump(INTERCEPTED, f, indent=2, default=str)
        print("\nSaved to tools/stake_raw.json")
        
        browser.close()

if __name__ == '__main__':
    run()
