"""
BTTS market ID discovery tool.
Intercepts live API responses from BetKing, Betway, Betpawa, and 1xBet
to find the correct BTTS market identifiers.
"""
import json
import time
import re
from playwright.sync_api import sync_playwright

results = {}


def find_btts_keywords(obj, path='', depth=0):
    """Recursively search a parsed JSON object for BTTS-related fields."""
    if depth > 15:
        return []
    hits = []
    btts_words = {'btts', 'both teams', 'gg', 'goal/goal', 'goal goal', 'bts',
                  'both score', 'both team'}
    if isinstance(obj, dict):
        for k, v in obj.items():
            new_path = f'{path}.{k}' if path else str(k)
            # Check key names
            if any(w in str(k).lower() for w in btts_words):
                hits.append((new_path, v))
            # Check string values
            if isinstance(v, str) and any(w in v.lower() for w in btts_words):
                hits.append((new_path, v))
            hits.extend(find_btts_keywords(v, new_path, depth + 1))
    elif isinstance(obj, list):
        for i, item in enumerate(obj[:20]):  # limit list scanning
            hits.extend(find_btts_keywords(item, f'{path}[{i}]', depth + 1))
    return hits


# ── BetKing ───────────────────────────────────────────────────────────────────
def discover_betking():
    print('\n=== BetKing ===')
    found = {}
    with sync_playwright() as pw:
        browser = pw.chromium.launch(headless=True, args=['--no-sandbox'])
        page = browser.new_page()

        def handle_response(response):
            if 'prematch/mostpopularsports' in response.url:
                try:
                    data = response.json()
                    # data[0]['AreaMatches'][0]['Items'][0]['OddsCollection']
                    items = data[0]['AreaMatches'][0]['Items']
                    for item in items[:5]:
                        for oc in item.get('OddsCollection', []):
                            ot = oc.get('OddsType', {})
                            name = ot.get('OddsTypeName', '') or ot.get('Name', '')
                            type_id = ot.get('OddsTypeID')
                            if any(w in name.lower() for w in ['btts', 'both teams', 'gg', 'goal/goal', 'goal goal', 'both score']):
                                found['market'] = {'OddsTypeID': type_id, 'name': name}
                                sample_odds = oc.get('MatchOdds', [])[:3]
                                found['sample_odds'] = [
                                    {
                                        'OddName': mo.get('OddAttribute', {}).get('OddName'),
                                        'SpecialValue': mo.get('OddAttribute', {}).get('SpecialValue'),
                                        'OddOutcome': mo.get('Outcome', {}).get('OddOutcome'),
                                    }
                                    for mo in sample_odds
                                ]
                except Exception as e:
                    pass

        page.on('response', handle_response)
        page.goto('https://www.betking.com/sports/s/football/', wait_until='networkidle', timeout=40000)
        time.sleep(3)
        browser.close()

    if found:
        print(f"  BTTS market: {json.dumps(found, indent=4)}")
    else:
        print("  BTTS not found in API response — may need to scroll/filter on page")
    results['betking'] = found


# ── Betway ────────────────────────────────────────────────────────────────────
def discover_betway():
    print('\n=== Betway ===')
    found = {}
    with sync_playwright() as pw:
        browser = pw.chromium.launch(headless=True, args=['--no-sandbox'])
        page = browser.new_page()

        def handle_response(response):
            if 'BetBook/Highlights' in response.url or 'betwayafrica' in response.url:
                try:
                    data = response.json()
                    markets = data.get('markets', [])
                    for m in markets:
                        name = m.get('name', '')
                        if any(w in name.lower() for w in ['btts', 'both teams', 'gg', 'goal/goal', 'both score', 'both team']):
                            found['market_name'] = name
                            found['sample_market'] = {k: v for k, v in m.items() if k != 'squashedMarketIds'}
                            # Find outcomes for this market
                            mid = m.get('marketId')
                            outcomes = [o for o in data.get('outcomes', []) if o.get('marketId') == mid][:4]
                            found['sample_outcomes'] = outcomes
                            break
                    # Also dump all unique market names so we can search
                    if 'all_market_names' not in found:
                        found['all_market_names'] = list({m.get('name') for m in markets})
                except Exception:
                    pass

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

    if found:
        btts_name = found.get('market_name')
        if btts_name:
            print(f"  BTTS market name: {btts_name!r}")
            print(f"  Sample outcomes: {json.dumps(found.get('sample_outcomes', []), indent=4)}")
        else:
            names = found.get('all_market_names', [])
            print(f"  BTTS not identified. All market names seen:\n  {names}")
    else:
        print("  No Highlights API response captured")
    results['betway'] = found


# ── Betpawa ───────────────────────────────────────────────────────────────────
def discover_betpawa():
    print('\n=== Betpawa ===')
    found = {}
    FETCH_JS = """
    async () => {
        const query = JSON.stringify({
            queries: [{
                query: {eventType: 'UPCOMING', categories: ['2'], zones: {}, hasOdds: true},
                view: {marketTypes: []},
                skip: 0, take: 5
            }]
        });
        const resp = await fetch(
            'https://www.betpawa.ng/api/sportsbook/v3/events/lists/by-queries?q=' + encodeURIComponent(query),
            {method: 'GET', credentials: 'include',
             headers: {'Accept': 'application/json', 'devicetype': 'web',
                       'x-pawa-language': 'en', 'x-pawa-brand': 'betpawa-nigeria'}}
        );
        return await resp.json();
    }
    """
    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)

        # Get sample event to see all market type IDs
        try:
            data = page.evaluate(FETCH_JS)
            events = (data.get('responses', [{}])[0]).get('responses', [])
            if events:
                ev = events[0]
                print(f"  Sample event: {ev.get('name', 'unknown')}")
                all_market_types = []
                for mkt in ev.get('markets', []):
                    mt = mkt.get('marketType', {})
                    all_market_types.append({'id': mt.get('id'), 'name': mt.get('name')})
                print(f"  Market types in sample event:\n  {json.dumps(all_market_types, indent=4)}")
                found['market_types'] = all_market_types

                # Look for BTTS
                for mt in all_market_types:
                    name = (mt.get('name') or '').lower()
                    if any(w in name for w in ['btts', 'both teams', 'gg', 'goal/goal', 'both score']):
                        found['btts_market'] = mt
                        print(f"  FOUND BTTS: {mt}")
        except Exception as e:
            print(f"  Error: {e}")

        # Now fetch with all discovered market type IDs to see BTTS odds
        if not found.get('btts_market'):
            # Try fetching a single event with all market types to see BTTS
            print("  BTTS not in default markets. Fetching event detail to see all markets...")
            EVENTS_JS = """
            async () => {
                const resp = await fetch(
                    'https://www.betpawa.ng/api/sportsbook/v3/events/lists/by-queries?q=' + encodeURIComponent(JSON.stringify({
                        queries: [{
                            query: {eventType: 'UPCOMING', categories: ['2'], zones: {}, hasOdds: true},
                            view: {marketTypes: []},
                            skip: 0, take: 1
                        }]
                    })),
                    {credentials: 'include',
                     headers: {'Accept': 'application/json', 'devicetype': 'web',
                               'x-pawa-language': 'en', 'x-pawa-brand': 'betpawa-nigeria'}}
                );
                const d = await resp.json();
                const evId = d?.responses?.[0]?.responses?.[0]?.id;
                if (!evId) return null;
                const r2 = await fetch(
                    'https://www.betpawa.ng/api/sportsbook/v3/events/' + evId + '/markets',
                    {credentials: 'include',
                     headers: {'Accept': 'application/json', 'devicetype': 'web',
                               'x-pawa-language': 'en', 'x-pawa-brand': 'betpawa-nigeria'}}
                );
                return await r2.json();
            }
            """
            try:
                detail = page.evaluate(EVENTS_JS)
                if detail:
                    mts = []
                    for mkt in (detail if isinstance(detail, list) else detail.get('markets', [])):
                        mt = mkt.get('marketType', {})
                        name = mt.get('name', '')
                        mts.append({'id': mt.get('id'), 'name': name})
                        if any(w in name.lower() for w in ['btts', 'both teams', 'gg', 'goal', 'both score']):
                            found['btts_market'] = mt
                            # Get prices
                            prices = []
                            for row in mkt.get('row', []):
                                prices.extend(row.get('prices', []))
                            found['btts_prices'] = prices[:4]
                            print(f"  FOUND BTTS in event detail: {mt}")
                            print(f"  Prices: {json.dumps(prices[:4], indent=4)}")
                    if not found.get('btts_market'):
                        print(f"  All market types in event detail:")
                        for mt in mts:
                            print(f"    {mt}")
                        found['all_event_market_types'] = mts
            except Exception as e:
                print(f"  Event detail error: {e}")

        browser.close()
    results['betpawa'] = found


# ── 1xBet ─────────────────────────────────────────────────────────────────────
def discover_1xbet():
    print('\n=== 1xBet ===')
    found = {}
    with sync_playwright() as pw:
        browser = pw.chromium.launch(headless=True, args=['--no-sandbox'])
        page = browser.new_page()

        captured = {}

        def handle_response(response):
            if 'Get1x2_VZip' in response.url or 'LineFeed' in response.url:
                try:
                    data = response.json()
                    events = data.get('Value', [])
                    if events and 'raw_sample' not in captured:
                        captured['raw_sample'] = events[:2]
                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()

    # Analyse the E[] array for BTTS G group
    if captured.get('raw_sample'):
        all_groups = {}
        for ev in captured['raw_sample']:
            for entry in ev.get('E', []):
                g = entry.get('G')
                t = entry.get('T')
                c = entry.get('C')
                n = entry.get('N', '')
                if g not in all_groups:
                    all_groups[g] = {'sample_entries': [], 'N': n}
                all_groups[g]['sample_entries'].append({'T': t, 'C': c})

        print(f"  All G-groups seen in E[] across 2 events:")
        for g, info in sorted(all_groups.items()):
            print(f"    G={g}: sample T-values={[e['T'] for e in info['sample_entries'][:5]]}")

        # Find BTTS group — look for G with exactly 2 T-values and no specifier (P field)
        print("\n  Looking for BTTS (G with 2 outcomes, no P specifier)...")
        for g, info in sorted(all_groups.items()):
            if g in (1, 17, 101):  # skip known markets
                continue
            t_vals = list({e['T'] for e in info['sample_entries']})
            if len(t_vals) == 2:
                print(f"    Candidate G={g}: T-values={sorted(t_vals)}")
                found[f'G{g}'] = {'T_values': sorted(t_vals)}

        found['all_groups'] = {str(g): [e['T'] for e in info['sample_entries'][:3]]
                               for g, info in all_groups.items()}
    else:
        print("  No LineFeed response captured")
    results['1xbet'] = found


if __name__ == '__main__':
    discover_betking()
    discover_betway()
    discover_betpawa()
    discover_1xbet()

    print('\n\n========== SUMMARY ==========')
    print(json.dumps(results, indent=2, default=str))
