"""World.xyz binary-market integration for the football pipeline.

The market catalog (`markets-api-proxy.world-xyz.workers.dev/api/v1/markets`) is
Cloudflare-gated to the world.xyz frontend session — even stealth proxies get
403 — so price fetching is not possible from this box. Instead:

1. picks.py prices every upcoming fixture into binary markets
   (win / over-under 2.5 / BTTS) and writes world_prices.json.
2. You read the YES price in Phantom, then:
   - compare it against the fair price in today's report, or
   - run `python3 world_check.py "Team A vs Team B" <price> [market]`
     for an instant verdict (BUY YES / BUY NO / PASS).

Feeding skeleton: the day the API opens up (or via a session-cookie channel),
`fetch_prices()` drops in and the manual step disappears.
"""
import json
import os

HERE = os.path.dirname(os.path.abspath(__file__))
PRICES_FILE = os.path.join(HERE, "world_prices.json")

MARKET_LABELS = {
    "home_win": "Home to win",
    "away_win": "Away to win",
    "over_2_5": "Over 2.5 goals",
    "under_2_5": "Under 2.5 goals",
    "btts": "Both teams to score",
}


def save_prices(rows):
    with open(PRICES_FILE, "w") as f:
        json.dump(rows, f, ensure_ascii=False, indent=1)


def load_prices():
    if not os.path.exists(PRICES_FILE):
        return []
    with open(PRICES_FILE) as f:
        return json.load(f)


def find_match(haystack, match_key):
    """Fuzzy match a 'Team A vs Team B' string onto price rows."""
    from sources import normalize_team
    a, b = [normalize_team(x.strip()) for x in match_key.split("vs", 1)]
    best, best_score = None, 0.0
    for row in haystack:
        na, nb = normalize_team(row["home"]), normalize_team(row["away"])
        score = (1 if (na == a or na in a or a in na) else 0) \
              + (1 if (nb == b or nb in b or b in nb) else 0)
        if score > best_score:
            best, best_score = row, score
    return best if best_score >= 2 else None


def verdict_for(row, market, price, spread=0.02, edge_min=0.05):
    """row: world_prices entry; market: key like 'home_win'; price: quoted YES price."""
    from model import world_verdict
    model_p = row["markets"].get(market)
    if model_p is None:
        return f"Unknown market '{market}'. Available: {', '.join(MARKET_LABELS)}"
    v = world_verdict(model_p, price, spread=spread, edge_min=edge_min)
    label = MARKET_LABELS.get(market, market)
    if v["action"] == "BUY YES":
        return (f"{label}: model {model_p:.0%} vs price {price:.0%} "
                f"-> BUY YES at <= {v['price_at_most']:.0%} (edge {v['edge']:.0%})")
    if v["action"] == "BUY NO":
        return (f"{label}: model {model_p:.0%} vs price {price:.0%} "
                f"-> BUY NO at >= {v['price_at_least']:.0%} (edge {v['edge']:.0%})")
    return (f"{label}: model {model_p:.0%} vs price {price:.0%} -> PASS "
            f"(edge yes {v.get('edge_yes', 0):+.0%}, no {v.get('edge_no', 0):+.0%})")