"""
Discover Bangbet groupIndex values for football markets.

Tries groupIndex 0–6 for football and prints the first market's
name + outcome IDs so we can identify DC, BTTS, etc.

Usage:
    python3 tools/discover_bangbet_groups.py
"""
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

import requests

_API_URL = 'https://bet-api.bangbet.com/api/bet/match/list'
_HEADERS = {
    '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'
    ),
    'Accept':       'application/json',
    'Content-Type': 'application/json',
    'Origin':       'https://www.bangbet.com',
    'Referer':      'https://www.bangbet.com/',
}

FOOTBALL_SPORT_ID = 'sr:sport:1'


def fetch_group(group_index: int, producer: int = 3):
    payload = {
        'sportId':      FOOTBALL_SPORT_ID,
        'groupIndex':   group_index,
        'tournamentId': '',
        'producer':     producer,
        'position':     17,
        'beginTime':    '',
        'highLight':    True,
        'endTime':      '',
        'showMarket':   True,
        'timeZone':     '+1',
        'page':         1,
        'sortType':     1,
        'pageSize':     3,   # only need a few matches
        'country':      'ng',
        'pageNo':       1,
        'dataGroup':    False,
    }
    resp = requests.post(_API_URL, json=payload, headers=_HEADERS, timeout=20)
    resp.raise_for_status()
    return resp.json()


def inspect(group_index: int, producer: int = 3):
    print(f'\n── groupIndex={group_index}  producer={producer} ──────────────────')
    try:
        data = fetch_group(group_index, producer)
    except Exception as ex:
        print(f'  ERROR: {ex}')
        return

    if data.get('result') != 1:
        print(f'  result={data.get("result")}  info={data.get("info")}')
        return

    matches = (data.get('data') or {}).get('data') or []
    if not matches:
        print('  (no matches returned)')
        return

    # Show first match's markets
    m = matches[0]
    print(f'  Match: {m.get("homeTeamName")} vs {m.get("awayTeamName")}')
    for mkt_group in m.get('marketList', []):
        for market in mkt_group.get('markets', []):
            name       = market.get('marketName') or market.get('name') or '?'
            specifiers = market.get('specifiers', '')
            active     = market.get('active')
            status     = market.get('marketStatus')
            outcomes   = market.get('outcomes', [])
            oc_summary = [(str(o.get('id')), o.get('desc') or o.get('name'), o.get('odds'))
                          for o in outcomes]
            print(f'  Market: {name!r:40s}  specifiers={specifiers!r:15s}  '
                  f'active={active}  status={status}')
            for oid, desc, odds in oc_summary:
                print(f'    outcome id={oid:<5} desc={str(desc):<30} odds={odds}')


if __name__ == '__main__':
    print('Scanning groupIndex 0–6 for football (prematch, producer=3)...')
    for gi in range(7):
        inspect(gi)

    print('\n\nScanning groupIndex 0–6 for football (live, producer=1)...')
    for gi in range(7):
        inspect(gi, producer=1)
