"""
Discover HT Over/Under market IDs for 1xBet, BetWinner, 22bet, and Betpawa.

1xBet/BetWinner/22bet: prints all G values present in a raw football event,
  with sample T, P, C values so we can identify which G is HT O/U.
Betpawa: prints all market_type_ids present in a football response.
"""
import sys
import os
import json
import time

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import requests

# ── 1xBet / BetWinner / 22bet (same LineFeed API) ─────────────────────────────

def discover_linefeed(name: str, base_url: str, partner: str):
    print(f"\n{'='*60}")
    print(f"  {name}  ({base_url})")
    print('='*60)
    session = requests.Session()
    session.headers.update({
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
        'Accept': 'application/json',
    })
    params = {
        'sports': '1', 'count': '20', 'lng': 'en',
        'mode': '4', 'country': '132',
        'getEmpty': 'true', 'virtualSports': 'true',
    }
    if partner and partner != '0':
        params['partner'] = partner
    try:
        url = base_url + '/Get1x2_VZip'
        r = session.get(url, params=params, timeout=15)
        r.raise_for_status()
        events = r.json().get('Value', [])
        print(f"  Got {len(events)} events")
    except Exception as ex:
        print(f"  ERROR: {ex}")
        return

    if not events:
        print("  No events returned")
        return

    # Collect all G values across all events
    g_samples = {}   # G → list of sample entries
    for ev in events[:10]:
        for entry in ev.get('E', []):
            g = entry.get('G')
            if g not in g_samples:
                g_samples[g] = []
            g_samples[g].append({
                'T': entry.get('T'), 'P': entry.get('P'),
                'C': entry.get('C'), 'CE': entry.get('CE')
            })

    print(f"\n  All G values found:")
    for g in sorted(g_samples.keys()):
        samples = g_samples[g][:3]
        # Summarise: distinct T values and P values
        ts = sorted(set(s['T'] for s in g_samples[g] if s.get('T') is not None))
        ps = sorted(set(s['P'] for s in g_samples[g] if s.get('P') is not None))
        print(f"    G={g:3d}  T={ts[:8]}  P={ps[:8]}")


# ── Betpawa ────────────────────────────────────────────────────────────────────

def discover_betpawa():
    print(f"\n{'='*60}")
    print("  Betpawa")
    print('='*60)
    try:
        from scrapers.betpawa import BetpawaScraper, MARKETS, SPORT_IDS
    except Exception as ex:
        print(f"  Cannot import BetpawaScraper: {ex}")
        return

    scraper = BetpawaScraper()

    # Known working IDs (anchor — ensures we always get events back)
    anchor = ['3743']  # 1X2-FT, always present

    # Focused scan: gaps in 3741 cluster + near-5000 (FT O/U neighbour)
    # 3744-3746 = between HT-1X2 and AH-1H; 5001-5008 = just above FT O/U
    candidates = ['3744', '3745', '3746', '3748', '3749', '3750',
                  '3751', '3752', '3753', '3754', '3755', '3757', '3758', '3759',
                  '5001', '5002', '5003', '5004', '5005', '5006', '5007', '5008']

    try:
        if not scraper._ensure_worker():
            print("  ERROR: worker failed to start")
            return
        worker = scraper.__class__._worker

        found = {}  # market_id → name

        # Scan in batches of 8 candidate IDs at a time
        batch_size = 8
        for i in range(0, len(candidates), batch_size):
            batch = anchor + candidates[i:i+batch_size]
            raw_events = worker.call(
                lambda page, b=batch: scraper._paginate(SPORT_IDS['football'], b, page=page),
                timeout=45,
            )
            for raw in (raw_events or []):
                for mkt in (raw.get('markets') or []):
                    mt = (mkt.get('marketType') or {})
                    mt_id = str(mt.get('id', ''))
                    mt_name = mt.get('name', '')
                    if mt_id and mt_id not in found and mt_id not in anchor:
                        found[mt_id] = mt_name
                        print(f"  FOUND: {mt_id}  →  {mt_name}")

        if not found:
            print("  No new market IDs found in scanned ranges.")
            print("  Known IDs: 3743=1X2-FT, 3741=HT-1X2, 5000=FT-O/U, etc.")
        else:
            print(f"\n  Summary of discovered IDs:")
            for mid, mname in sorted(found.items(), key=lambda x: int(x[0]) if x[0].isdigit() else 0):
                print(f"    {mid}  →  {mname}")

        scraper._reset_worker()
    except Exception as ex:
        print(f"  ERROR: {ex}")
        import traceback; traceback.print_exc()


if __name__ == '__main__':
    # 1xBet
    discover_linefeed('1xBet',    'https://1xbet.ng/service-api/LineFeed',     '159')
    # BetWinner (same API, different partner)
    discover_linefeed('BetWinner','https://betwinner.ng/service-api/LineFeed',  '3')
    # 22bet (no partner param needed)
    discover_linefeed('22bet',    'https://22bet.ng/service-api/LineFeed',      '0')
    # Betpawa
    discover_betpawa()
