"""
Round 3: Confirm Betpawa market 3795 price names + fix 1xBet GE parsing + Betway deeper search.
"""
import json, time, re
from playwright.sync_api import sync_playwright


# ── Betpawa: confirm market 3795 price names ──────────────────────────────────
def confirm_betpawa():
    print('\n=== Betpawa: confirm BTTS market 3795 prices ===')
    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()
        page.goto('https://www.betpawa.ng/events', wait_until='domcontentloaded', timeout=35000)
        time.sleep(4)

        result = page.evaluate("""
        async () => {
            const query = JSON.stringify({
                queries: [{
                    query: {eventType: 'UPCOMING', categories: ['2'], zones: {}, hasOdds: true},
                    view: {marketTypes: ['3795']},
                    skip: 0, take: 5
                }]
            });
            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'}}
            );
            return await resp.json();
        }
        """)
        events = (result.get('responses', [{}])[0]).get('responses', [])
        print(f"  Events returned: {len(events)}")
        for ev in events[:3]:
            participants = ev.get('participants', [])
            home = next((p['name'] for p in participants if p.get('position') == 1), '?')
            away = next((p['name'] for p in participants if p.get('position') == 2), '?')
            print(f"  Event: {home} vs {away}")
            for mkt in ev.get('markets', []):
                mt = mkt.get('marketType', {})
                if str(mt.get('id')) == '3795':
                    prices = []
                    for row in mkt.get('row', []):
                        prices.extend(row.get('prices', []))
                    print(f"    Market: {mt.get('name')}")
                    for p in prices:
                        print(f"      name={p.get('name')!r:10} price={p.get('price')} suspended={p.get('suspended')} typeId={p.get('typeId')}")
        browser.close()


# ── 1xBet: properly parse GE market groups ────────────────────────────────────
def discover_1xbet_ge():
    print('\n=== 1xBet: GE market group names ===')
    with sync_playwright() as pw:
        browser = pw.chromium.launch(headless=True, args=['--no-sandbox'])
        page = browser.new_page()
        captured = []

        def on_response(r):
            if 'Get1x2_VZip' in r.url:
                try:
                    d = r.json()
                    captured.extend(d.get('Value', []))
                except Exception:
                    pass

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

        # Pick an event that's likely to have BTTS (big club match with many markets)
        # Sort by event ID descending to get more popular events
        if captured:
            # Try a few events to find one with GG market
            for ev in captured[:10]:
                eid = ev.get('I')
                o1, o2 = ev.get('O1', ''), ev.get('O2', '')
                url = (f"https://1xbet.ng/service-api/LineFeed/GetGameZip"
                       f"?id={eid}&lng=en&isSubGames=true&GroupEvents=true"
                       f"&countAddGames=1&partner=159&country=132")
                try:
                    r = page.goto(url, timeout=20000)
                    text = page.evaluate('() => document.body.innerText')
                    data = json.loads(text)
                    game = data.get('Value', {})
                    ge = game.get('GE', [])
                    if not isinstance(ge, list):
                        continue
                    print(f"\n  Event: {o1} vs {o2} (id={eid}) — {len(ge)} market groups")
                    for entry in ge:
                        if not isinstance(entry, dict):
                            continue
                        g = entry.get('G')
                        gn = entry.get('GN', '')
                        mn = entry.get('MN', '') or entry.get('N', '')
                        e_list = entry.get('E', [])
                        t_vals = [e.get('T') for e in e_list if isinstance(e, dict)]
                        name = gn or mn
                        if any(w in name.lower() for w in ['gg','both','btts','goal goal','both score']):
                            print(f"    *** BTTS CANDIDATE: G={g} name={name!r} T-values={t_vals[:5]}")
                            # Show full odds
                            for e in e_list[:3]:
                                print(f"        T={e.get('T')} C={e.get('C')} N={e.get('N', '')}")
                    # Print all 2-outcome groups with names
                    print(f"  2-outcome groups:")
                    for entry in ge:
                        if not isinstance(entry, dict):
                            continue
                        e_list = entry.get('E', [])
                        t_vals = list({e.get('T') for e in e_list if isinstance(e, dict)})
                        if len(t_vals) == 2:
                            g = entry.get('G')
                            name = entry.get('GN', '') or entry.get('MN', '') or entry.get('N', '')
                            print(f"    G={g:6} T={sorted(t_vals)} name={name!r}")
                    break  # found a parseable event
                except Exception as e:
                    print(f"  Event {eid} error: {e}")
                    continue
        browser.close()


# ── Betway: try event-specific market endpoint ────────────────────────────────
def discover_betway():
    print('\n=== Betway ===')
    with sync_playwright() as pw:
        browser = pw.chromium.launch(headless=True, args=['--no-sandbox'])
        page = browser.new_page()
        event_ids = []
        all_market_names = set()

        def on_response(r):
            if 'betwayafrica' in r.url:
                try:
                    d = r.json()
                    for ev in d.get('events', [])[:5]:
                        event_ids.append(ev.get('eventId'))
                    for m in d.get('markets', []):
                        all_market_names.add(m.get('name', ''))
                except Exception:
                    pass

        page.on('response', on_response)
        page.goto('https://www.betway.com.ng/sport/football', wait_until='networkidle', timeout=40000)
        time.sleep(3)

        print(f"  Captured event IDs: {event_ids[:5]}")
        print(f"  Market names from Highlights: {sorted(all_market_names)}")

        # Try fetching all markets for a specific event
        if event_ids:
            ev_id = event_ids[0]
            for market_type in ['[Both Teams to Score]', '[Both Teams To Score]',
                                 '[Goal Goal]', '[GG/NG]', '[GG]']:
                try:
                    result = page.evaluate(f"""
                    async () => {{
                        const params = new URLSearchParams({{
                            countryCode: 'NG', sportId: 'soccer',
                            Skip: '0', Take: '200', cultureCode: 'en-US',
                            boostedOnly: 'false',
                        }});
                        params.append('marketTypes', '{market_type}');
                        const r = await fetch(
                            'https://feeds-roa2.betwayafrica.com/br/_apis/sport/v1/BetBook/Highlights/?' + params,
                            {{headers: {{'Accept': 'application/json'}}}}
                        );
                        const d = await r.json();
                        return {{status: r.status, markets: d.markets?.map(m => m.name) || [], count: d.markets?.length || 0}};
                    }}
                    """)
                    if result.get('count', 0) > 0:
                        print(f"  marketType={market_type!r} → {result}")
                    else:
                        print(f"  marketType={market_type!r} → 0 markets (status {result.get('status')})")
                except Exception as e:
                    print(f"  Error with {market_type!r}: {e}")

        # Try the event-specific markets endpoint
        if event_ids:
            ev_id = event_ids[0]
            try:
                result = page.evaluate(f"""
                async () => {{
                    const r = await fetch(
                        'https://feeds-roa2.betwayafrica.com/br/_apis/sport/v1/BetBook/Events/{ev_id}/Markets/?countryCode=NG&cultureCode=en-US',
                        {{headers: {{'Accept': 'application/json', 'Origin': 'https://www.betway.com.ng'}}}}
                    );
                    return await r.json();
                }}
                """)
                if result:
                    mkts = result if isinstance(result, list) else result.get('markets', [])
                    print(f"\n  Event {ev_id} all markets ({len(mkts)}):")
                    for m in mkts:
                        name = m.get('name', '') if isinstance(m, dict) else str(m)
                        marker = ' <-- BTTS?' if any(w in name.lower() for w in ['btts','both','gg','goal','score']) else ''
                        print(f"    {name!r}{marker}")
            except Exception as e:
                print(f"  Event markets endpoint error: {e}")

        browser.close()


if __name__ == '__main__':
    confirm_betpawa()
    discover_1xbet_ge()
    discover_betway()
