"""
Discover Surebet247 market type IDs from the WS feed.

Navigates to the football prematch page, captures all WS frames,
then prints every unique market_type_id seen along with a sample
outcome structure — so we can identify DC, BTTS, etc.

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

import time
import collections
from scrapers.surebet247 import _Surebet247Worker, _decode_frame

BASE_SITE  = 'https://www.surebet247.com'
SPORT_SLUG = 'football'
LOAD_WAIT  = 25
SCROLL_CYCLES = 8


def scrape_all_market_types(page) -> dict:
    """Navigate to football page, capture frames, return all unique market types."""
    frames_recv = []
    frames_sent = []
    last_recv   = [time.time()]

    def handle_ws(ws):
        if 'direct-feed' not in ws.url:
            return
        ws.on('framereceived', lambda p: (frames_recv.append(p), last_recv.__setitem__(0, time.time())) if isinstance(p, bytes) else None)
        ws.on('framesent',     lambda p: frames_sent.append(p) if isinstance(p, bytes) else None)

    page.on('websocket', handle_ws)
    page.goto(f'{BASE_SITE}/sport/{SPORT_SLUG}', wait_until='domcontentloaded', timeout=60_000)
    time.sleep(8)
    for _ in range(SCROLL_CYCLES):
        page.mouse.wheel(0, 700)
        time.sleep(0.6)
    deadline = time.time() + LOAD_WAIT
    while time.time() < deadline:
        time.sleep(1)
        if time.time() - last_recv[0] > 3.0 and frames_recv:
            break
    try:
        page.remove_listener('websocket', handle_ws)
    except Exception:
        pass

    print(f'Captured {len(frames_recv)} recv / {len(frames_sent)} sent frames')

    # Build request-ID → method map from sent frames
    method_by_id = {}
    for frame in frames_sent:
        if not isinstance(frame, bytes):
            continue
        decoded = _decode_frame(frame)
        if decoded and isinstance(decoded, (list, tuple)) and len(decoded) >= 4 and decoded[0] == 4:
            method_by_id[str(decoded[2])] = str(decoded[3])

    market_ids = {rid for rid, m in method_by_id.items() if m == 'GetMainMarketsByProfileAndEventIds'}

    # market_type_id → list of sample outcome structures
    market_samples = collections.defaultdict(list)

    for frame in frames_recv:
        if not isinstance(frame, bytes):
            continue
        decoded = _decode_frame(frame)
        if not decoded or not isinstance(decoded, (list, tuple)) or decoded[0] != 2:
            continue
        if len(decoded) < 4:
            continue
        rid = str(decoded[2])
        if rid not in market_ids:
            continue

        reply_data = decoded[3]
        if not isinstance(reply_data, (list, tuple)) or len(reply_data) < 2 or not reply_data[0]:
            continue

        items = reply_data[1]
        if not isinstance(items, (list, tuple)):
            continue

        for item in items:
            if not isinstance(item, (list, tuple)) or len(item) < 3:
                continue
            item_key = item[1]
            if not isinstance(item_key, (list, tuple)) or len(item_key) < 3:
                continue

            market_type = item_key[2]
            market_val  = item[2]
            if not isinstance(market_val, (list, tuple)) or not market_val:
                continue
            selection_groups = market_val[0]
            if not isinstance(selection_groups, (list, tuple)):
                continue

            for group in selection_groups:
                if not isinstance(group, (list, tuple)) or len(group) < 2:
                    continue
                outcomes_raw = group[1]
                if not isinstance(outcomes_raw, (list, tuple)):
                    continue
                sample = []
                for oc in outcomes_raw:
                    if not isinstance(oc, (list, tuple)) or len(oc) < 2:
                        continue
                    oc_key  = oc[0]
                    price_c = oc[1]
                    if isinstance(oc_key, (list, tuple)) and oc_key:
                        sample.append({'type_id': oc_key[0], 'price': price_c})
                if sample:
                    market_samples[market_type].append(sample)

    return market_samples


if __name__ == '__main__':
    worker = _Surebet247Worker()
    print('Browser ready. Navigating to football page...')

    samples = worker.call(scrape_all_market_types, timeout=120)

    print(f'\nFound {len(samples)} unique market type IDs:\n')
    for mtype in sorted(samples.keys()):
        all_samples = samples[mtype]
        # Show one sample group's outcome type IDs
        sample = all_samples[0] if all_samples else []
        oc_types = [o['type_id'] for o in sample]
        prices   = [round(o['price'] / 100, 2) for o in sample]
        print(f'  market_type_id={mtype:<5}  count={len(all_samples):<5}  '
              f'outcome_type_ids={oc_types}  sample_prices={prices}')
