"""
从 Gamma /events 的 event + market 中解析 Polymarket 参考价（price to beat / final）。

兼容多种字段命名（camelCase / snake_case、event 与 market 层级）。
"""
from __future__ import annotations

import json
from typing import Any, Optional


def metadata_as_dict(raw: Any) -> dict[str, Any]:
    if raw is None:
        return {}
    if isinstance(raw, dict):
        return raw
    if isinstance(raw, str):
        try:
            d = json.loads(raw)
            return d if isinstance(d, dict) else {}
        except json.JSONDecodeError:
            return {}
    return {}


def float_or_none(x: Any) -> Optional[float]:
    if x is None or x == "":
        return None
    try:
        return float(x)
    except (TypeError, ValueError):
        return None


def extract_ref_prices(
    event: dict[str, Any], market: dict[str, Any]
) -> tuple[Optional[float], Optional[float]]:
    """
    返回 (price_to_beat, final_price)。
    未收盘时 final 通常为 None。
    """
    meta = metadata_as_dict(event.get("eventMetadata"))

    ptb_candidates = [
        meta.get("priceToBeat"),
        meta.get("price_to_beat"),
        meta.get("openPrice"),
        meta.get("open_price"),
        meta.get("open"),
        meta.get("strike"),
        meta.get("strikePrice"),
        meta.get("referencePrice"),
        market.get("openPrice"),
        market.get("open_price"),
        market.get("priceToBeat"),
        market.get("price_to_beat"),
        market.get("line"),
        market.get("strike"),
    ]
    fin_candidates = [
        meta.get("finalPrice"),
        meta.get("final_price"),
        meta.get("closePrice"),
        meta.get("close_price"),
        meta.get("resolvedPrice"),
        market.get("finalPrice"),
        market.get("final_price"),
        market.get("closePrice"),
        market.get("close_price"),
    ]

    ptb = next((float_or_none(c) for c in ptb_candidates if c is not None), None)
    fin = next((float_or_none(c) for c in fin_candidates if c is not None), None)
    return ptb, fin
