"""
Round 2 BTTS discovery: 1xBet G-group naming, Betway and Betpawa retry.
"""
import json
import time
from playwright.sync_api import sync_playwright


# ── 1xBet: identify G-group names via market description API ─────────────────
def discover_1xbet_groups():
    print('\n=== 1xBet: identify G-group market names ===')
    with sync_playwright() as pw:
        browser = pw.chromium.launch(headless=True, args=['--no-sandbox'])
        page = browser.new_page()
        captured_events = []

        def handle_response(response):
            if 'Get1x2_VZip' in response.url:
                try:
                    data = response.json()
                    captured_events.extend(data.get('Value', []))
                except Exception:
                    pass

        page.on('response', handle_response)
        page.goto('https://1xbet.ng/en/line/football', wait_until='networkidle', timeout=40000)
        time.sleep(3)
        browser.close()

    # The E[] entries have a field 'N' which is NOT the market name in this structure.
    # Instead, try fetching event detail via the event-specific API endpoint.
    # 1xBet event detail: /service-api/LineFeed/GetGameZip?id={I}&lng=en&isSubGames=true&GroupEvents=true&countAddGames=1&partner=159&country=132
    if not captured_events:
        print("  No events captured")
        return

    sample_event_id = captured_events[0].get('I')
    print(f"  Sample event ID: {sample_event_id}")
    print(f"  Event: {captured_events[0].get('O1')} vs {captured_events[0].get('O2')}")

    # Fetch event detail
    with sync_playwright() as pw:
        browser = pw.chromium.launch(headless=True, args=['--no-sandbox'])
        page = browser.new_page()

        detail_url = (
            f"https://1xbet.ng/service-api/LineFeed/GetGameZip"
            f"?id={sample_event_id}&lng=en&isSubGames=true&GroupEvents=true"
            f"&countAddGames=1&partner=159&country=132"
        )
        print(f"  Fetching: {detail_url}")
        try:
            r = page.goto(detail_url, timeout=20000)
            content = page.content()
            # Extract JSON from page content
            import re
            match = re.search(r'\{.*\}', content, re.DOTALL)
            if match:
                data = json.loads(match.group())
                game_data = data.get('Value', {})

                # Look for market groups with names
                params = game_data.get('P', {})  # P often has parameters
                ge = game_data.get('GE', [])      # GE = game events/markets

                print(f"\n  Keys in Value: {list(game_data.keys())[:20]}")

                # Find GG/BTTS in the detailed response
                def search_btts(obj, path='', depth=0):
                    if depth > 8:
                        return
                    btts = {'btts','gg','both teams','goal goal','goal/goal','both score'}
                    if isinstance(obj, dict):
                        for k, v in obj.items():
                            p = f'{path}.{k}'
                            if isinstance(v, str) and any(w in v.lower() for w in btts):
                                print(f"    HIT: {p} = {v!r}")
                            search_btts(v, p, depth+1)
                    elif isinstance(obj, list):
                        for i, item in enumerate(obj[:10]):
                            search_btts(item, f'{path}[{i}]', depth+1)

                print("\n  Searching for BTTS keywords in event detail:")
                search_btts(game_data)

                # Also dump all GE entries (market groups)
                if ge:
                    print(f"\n  GE (market groups) — {len(ge)} entries:")
                    for entry in ge[:30]:
                        gid = entry.get('G')
                        name = entry.get('GN') or entry.get('N') or entry.get('MN', '')
                        t_vals = [e.get('T') for e in entry.get('E', [])]
                        print(f"    G={gid} name={name!r} T-values={t_vals[:5]}")
        except Exception as e:
            print(f"  Error: {e}")

        browser.close()


# ── Betway: try football-specific page and capture all market names ───────────
def discover_betway():
    print('\n=== Betway ===')
    found_markets = set()
    btts_found = {}
    with sync_playwright() as pw:
        browser = pw.chromium.launch(headless=True, args=['--no-sandbox'])
        page = browser.new_page()

        def handle_response(response):
            url = response.url
            if 'betwayafrica' in url or 'betway' in url.lower():
                try:
                    data = response.json()
                    if isinstance(data, dict):
                        for m in data.get('markets', []):
                            name = m.get('name', '')
                            found_markets.add(name)
                            if any(w in name.lower() for w in ['btts','both teams','gg','goal','both score']):
                                btts_found['market'] = m
                                ev_id = m.get('eventId')
                                ocs = [o for o in data.get('outcomes', []) if o.get('marketId') == m.get('marketId')]
                                btts_found['outcomes'] = ocs[:4]
                except Exception:
                    pass

        page.on('response', handle_response)

        # Try with BTTS market type explicitly
        page.goto('https://www.betway.com.ng/sport/football', wait_until='networkidle', timeout=40000)
        time.sleep(2)

        # Also try fetching via JS with BTTS market type
        try:
            data = page.evaluate("""
            async () => {
                const params = new URLSearchParams({
                    countryCode: 'NG', sportId: 'soccer',
                    Skip: '0', Take: '200',
                    cultureCode: 'en-US', boostedOnly: 'false',
                });
                params.append('marketTypes', '[Both Teams to Score]');
                params.append('marketTypes', '[Win/Draw/Win]');
                const r = await fetch(
                    'https://feeds-roa2.betwayafrica.com/br/_apis/sport/v1/BetBook/Highlights/?' + params,
                    {headers: {'Accept': 'application/json'}}
                );
                return await r.json();
            }
            """)
            if data:
                for m in data.get('markets', []):
                    name = m.get('name', '')
                    found_markets.add(name)
                    if any(w in name.lower() for w in ['btts','both teams','gg','goal','both score','score']):
                        btts_found['market_js'] = m
                        ocs = [o for o in data.get('outcomes', []) if o.get('marketId') == m.get('marketId')]
                        btts_found['outcomes_js'] = ocs[:4]
        except Exception as e:
            print(f"  JS fetch error: {e}")

        browser.close()

    print(f"  All market names seen: {sorted(found_markets)}")
    if btts_found:
        print(f"  BTTS market: {json.dumps(btts_found, indent=4)}")
    else:
        print("  BTTS not found — need to find market type string")


# ── Betpawa: intercept network traffic directly ───────────────────────────────
def discover_betpawa():
    print('\n=== Betpawa ===')
    all_market_types = {}
    btts_found = {}

    with sync_playwright() as pw:
        browser = pw.chromium.launch(headless=True, args=['--no-sandbox'])
        ctx = browser.new_context(locale='en-US')
        page = ctx.new_page()

        def handle_response(response):
            if 'betpawa' in response.url and 'api' in response.url:
                try:
                    data = response.json()
                    # Scan for market types in any structure
                    def scan(obj, depth=0):
                        if depth > 8 or not obj:
                            return
                        if isinstance(obj, dict):
                            mt = obj.get('marketType')
                            if mt and isinstance(mt, dict):
                                mid = mt.get('id')
                                mname = mt.get('name', '')
                                all_market_types[mid] = mname
                                if any(w in mname.lower() for w in ['btts','both teams','gg','goal','both score']):
                                    btts_found['id'] = mid
                                    btts_found['name'] = mname
                                    # Get prices
                                    prices = []
                                    for row in obj.get('row', []):
                                        prices.extend(row.get('prices', []))
                                    btts_found['prices'] = prices[:4]
                            for v in obj.values():
                                scan(v, depth+1)
                        elif isinstance(obj, list):
                            for item in obj[:20]:
                                scan(item, depth+1)
                    scan(data)
                except Exception:
                    pass

        page.on('response', handle_response)
        page.goto('https://www.betpawa.ng/football', wait_until='networkidle', timeout=40000)
        time.sleep(5)

        # Also try fetching via JS with all market types empty (gets defaults)
        FETCH_JS = """
        async () => {
            const query = JSON.stringify({
                queries: [{
                    query: {eventType: 'UPCOMING', categories: ['2'], zones: {}, hasOdds: true},
                    view: {marketTypes: []},
                    skip: 0, take: 3
                }]
            });
            const resp = await fetch(
                'https://www.betpawa.ng/api/sportsbook/v3/events/lists/by-queries?q=' + encodeURIComponent(query),
                {credentials: 'include',
                 headers: {'Accept': 'application/json', 'devicetype': 'web',
                           'x-pawa-language': 'en', 'x-pawa-brand': 'betpawa-nigeria'}}
            );
            const d = await resp.json();
            // Get first event ID
            const evId = d?.responses?.[0]?.responses?.[0]?.id;
            if (!evId) return {error: 'no event id', data: d};
            // Fetch full market list for this event
            const r2 = await fetch(
                'https://www.betpawa.ng/api/sportsbook/v3/events/' + evId,
                {credentials: 'include',
                 headers: {'Accept': 'application/json', 'devicetype': 'web',
                           'x-pawa-language': 'en', 'x-pawa-brand': 'betpawa-nigeria'}}
            );
            return {eventId: evId, eventDetail: await r2.json()};
        }
        """
        try:
            result = page.evaluate(FETCH_JS)
            print(f"  JS fetch result keys: {list(result.keys()) if isinstance(result, dict) else result}")
            if isinstance(result, dict) and result.get('eventDetail'):
                detail = result['eventDetail']
                for mkt in (detail.get('markets') or []):
                    mt = mkt.get('marketType', {})
                    mid = mt.get('id')
                    mname = mt.get('name', '')
                    all_market_types[mid] = mname
                    if any(w in mname.lower() for w in ['btts','both teams','gg','goal','both score']):
                        btts_found['id'] = mid
                        btts_found['name'] = mname
                        prices = []
                        for row in mkt.get('row', []):
                            prices.extend(row.get('prices', []))
                        btts_found['prices'] = prices[:4]
                print(f"  Event detail market count: {len(detail.get('markets', []))}")
        except Exception as e:
            print(f"  JS error: {e}")

        browser.close()

    print(f"\n  All market types seen ({len(all_market_types)}):")
    for mid, mname in sorted(all_market_types.items(), key=lambda x: str(x[0])):
        marker = ' <-- BTTS?' if any(w in mname.lower() for w in ['btts','both','gg','goal','score']) else ''
        print(f"    id={mid!r:20} name={mname!r}{marker}")
    if btts_found:
        print(f"\n  BTTS: {btts_found}")


if __name__ == '__main__':
    discover_1xbet_groups()
    discover_betway()
    discover_betpawa()
