"""
Round 4: Betway BTTS outcome names + 1xBet with a club match.
"""
import json, time
from playwright.sync_api import sync_playwright


def betway_btts_outcomes():
    print('\n=== Betway BTTS outcome names ===')
    with sync_playwright() as pw:
        browser = pw.chromium.launch(headless=True, args=['--no-sandbox'])
        page = browser.new_page()
        page.goto('https://www.betway.com.ng/sport/football', wait_until='networkidle', timeout=40000)
        time.sleep(2)

        result = page.evaluate("""
        async () => {
            const params = new URLSearchParams({
                countryCode: 'NG', sportId: 'soccer',
                Skip: '0', Take: '10', cultureCode: 'en-US', boostedOnly: 'false',
            });
            params.append('marketTypes', '[Both Teams To Score]');
            const r = await fetch(
                'https://feeds-roa2.betwayafrica.com/br/_apis/sport/v1/BetBook/Highlights/?' + params,
                {headers: {'Accept': 'application/json', 'Origin': 'https://www.betway.com.ng',
                            'Referer': 'https://www.betway.com.ng/'}}
            );
            return await r.json();
        }
        """)
        events = result.get('events', [])[:3]
        markets = {m['marketId']: m for m in result.get('markets', [])}
        outcomes = result.get('outcomes', [])
        prices = {p['outcomeId']: p['priceDecimal'] for p in result.get('prices', []) if p.get('priceDecimal')}

        for ev in events:
            ev_id = ev.get('eventId')
            home = ev.get('homeTeam', '')
            away = ev.get('awayTeam', '')
            print(f"  {home} vs {away}")
            ev_markets = [m for m in result.get('markets', []) if m.get('eventId') == ev_id and m.get('name') == '[Both Teams To Score]']
            for m in ev_markets[:1]:
                mid = m.get('marketId')
                is_parent = m.get('isSquashedParent', False)
                print(f"    Market id={mid} isSquashedParent={is_parent}")
                ev_outcomes = [o for o in outcomes if o.get('marketId') == mid]
                for o in ev_outcomes:
                    print(f"      outcome name={o.get('name')!r:10} id={o.get('outcomeId')} isTradingActive={o.get('isTradingActive')} price={prices.get(o.get('outcomeId'))}")
        browser.close()


def onexbet_club_match():
    print('\n=== 1xBet: finding a club match with BTTS ===')
    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)

        print(f"  Total events captured: {len(captured)}")
        # Filter to events that have G=62 entries in E[]
        # G=62 is our BTTS candidate from round 1
        for ev in captured[:50]:
            e_groups = {}
            for entry in ev.get('E', []):
                g = entry.get('G')
                e_groups.setdefault(g, []).append(entry)

            # Check for our candidate groups
            btts_candidates = [g for g in [2, 15, 19, 62] if g in e_groups]
            if btts_candidates and 1 in e_groups:  # has 1X2 too (it's a real match)
                eid = ev.get('I')
                o1, o2 = ev.get('O1', ''), ev.get('O2', '')
                print(f"\n  Event: {o1} vs {o2} (id={eid})")
                print(f"  G groups present: {sorted(e_groups.keys())}")
                for g in btts_candidates:
                    entries = e_groups[g]
                    t_c = [(e.get('T'), e.get('C')) for e in entries]
                    print(f"    G={g}: {t_c}")

                # Fetch GetGameZip for this event
                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 isinstance(ge, list) and ge:
                        print(f"\n  GetGameZip GE entries ({len(ge)}):")
                        for entry in ge:
                            if not isinstance(entry, dict):
                                continue
                            g = entry.get('G')
                            gn = entry.get('GN', '') or entry.get('MN', '') or entry.get('N', '')
                            e_list = entry.get('E', [])
                            if not isinstance(e_list, list):
                                continue
                            t_vals = sorted({e.get('T') for e in e_list if isinstance(e, dict)})
                            if len(t_vals) == 2:
                                btts_flag = ' ← BTTS?' if any(w in gn.lower() for w in ['gg','both','goal','score','btts']) else ''
                                print(f"    G={g:6} name={gn!r:40} T={t_vals}{btts_flag}")
                    else:
                        # GE is not a list — inspect structure
                        print(f"  GE type: {type(ge)}, keys if dict: {list(ge.keys())[:10] if isinstance(ge, dict) else 'N/A'}")
                except Exception as e:
                    print(f"  GetGameZip error: {e}")
                break  # just need one good event

        browser.close()


if __name__ == '__main__':
    betway_btts_outcomes()
    onexbet_club_match()
