"""services/live_sports.py

Live cricket scores - from ESPN's public scoreboard, with the time they were
fetched - never from a web-search snippet.

Why (Oct 16): "live cricket score" was answered "I'm not able to pull a
real-time cricket score" (search snippets carry no live scores), and earlier
runs pointed at Cricinfo / Cricbuzz or wrote raw search JSON.

Source: ESPN's scorepanel feed (site.api.espn.com/.../cricket/scorepanel) -
live, finished and scheduled matches across competitions, each with its
status ("Live", "Result", "Scheduled"), the score line ESPN shows and its
summary ("Heat won by 6 wkts", "require 117 runs"). It is an unofficial,
keyless endpoint: if it cannot be reached the answer says so - no guess.
"""
import logging
import os
import re
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

import httpx

logger = logging.getLogger(__name__)

_CRICKET_URL = os.getenv("LIVE_CRICKET_URL",
                         "https://site.api.espn.com/apis/site/v2/sports/cricket/scorepanel")
_TIMEOUT = float(os.getenv("LIVE_INFO_TIMEOUT_SECONDS", "6"))
_MAX_LINES = 8

_CRICKET_NATIONS = ("india", "pakistan", "australia", "england", "new zealand", "south africa",
                    "sri lanka", "bangladesh", "afghanistan", "west indies", "zimbabwe", "ireland",
                    "netherlands", "scotland", "nepal", "uae", "usa", "canada", "oman", "namibia")
_LEAGUES = r"ipl|psl|bbl|big\s+bash|cpl|the\s+hundred|wpl|sa20|ilt20|ranji|t20i?|odi|test\s+match|world\s+cup"

_CRICKET_RE = re.compile(rf"\b(?:cricket|{_LEAGUES})\b", re.IGNORECASE)
_SCORE_WORD_RE = re.compile(r"\b(?:score|scores|scorecard|match|matches|result|results|playing|"
                            r"live|today|fixtures?|schedule|kaun\s+jeeta|who\s+won|who\s+is\s+winning)\b",
                            re.IGNORECASE)
_VS_RE = re.compile(rf"\b(?P<a>{'|'.join(_CRICKET_NATIONS)})\s+(?:vs?\.?|versus|and|v)\s+"
                    rf"(?P<b>{'|'.join(_CRICKET_NATIONS)})\b", re.IGNORECASE)
_NATION_RE = re.compile(rf"\b(?P<n>{'|'.join(_CRICKET_NATIONS)})\b", re.IGNORECASE)


_NATION_MATCH_RE = re.compile(rf"\b(?:{'|'.join(_CRICKET_NATIONS)})\b(?:\s+(?:women|men|u19|under-19s?|a))?"
                              r"\s+(?:match|matches|score|scores|scorecard|result|results|game)\b",
                              re.IGNORECASE)


def parse(query: str, today=None):
    """{"kind": "cricket", "teams": [...], "day": date|None} for a live
    cricket question, else None. "india women match today" counts - in this
    product a country's "match" is cricket."""
    text = (query or "").strip()
    if not text:
        return None
    vs = _VS_RE.search(text)
    cricket = _CRICKET_RE.search(text) or _NATION_MATCH_RE.search(text)
    if not (cricket or (vs and _SCORE_WORD_RE.search(text))):
        return None
    if not _SCORE_WORD_RE.search(text) and not vs:
        # "what is cricket", "cricket rules" - not a scores question.
        return None
    if re.search(r"\b(?:rules?|history|how\s+to\s+play|invented|meaning|define)\b", text, re.IGNORECASE):
        return None
    teams = [vs.group("a").lower(), vs.group("b").lower()] if vs else \
        [m.group("n").lower() for m in _NATION_RE.finditer(text)]
    if re.search(r"\bwomen\b", text, re.IGNORECASE):
        teams.append("women")
    # A day: "yesterday cricket score", "cricket results on 13 oct". Live
    # (Oct 16): "yesterday cricket score" got 'I wasn't able to locate a
    # specific match-by-match score' from search snapshots.
    import services.live_info as live_info
    today = today or datetime.now(_app_tz()).date()
    _, day_text = live_info._split_day(live_info._fold_day_typos(text))
    day = live_info._resolve_day(day_text, today) if day_text else None
    return {"kind": "cricket", "teams": teams, "day": None if day == today else day}


def _app_tz():
    try:
        return ZoneInfo(os.getenv("QUOTA_TIMEZONE", "UTC"))
    except Exception:
        return ZoneInfo("UTC")


def _when(dt: datetime) -> str:
    local = dt.astimezone(_app_tz())
    return f"{local.strftime('%I:%M %p').lstrip('0')} {local.tzname()}"


def _events(feed: dict):
    for block in feed.get("scores") or []:
        league = ((block.get("leagues") or [{}])[0]).get("name") or ""
        for ev in block.get("events") or []:
            comp = (ev.get("competitions") or [{}])[0]
            status = ((ev.get("status") or {}).get("type") or {})
            try:
                start = datetime.fromisoformat(str(ev.get("date")).replace("Z", "+00:00"))
            except Exception:
                continue
            sides = []
            for c in comp.get("competitors") or []:
                team = (c.get("team") or {})
                sides.append({"name": team.get("displayName") or team.get("name") or "?",
                              "score": (c.get("score") or "").strip(),
                              "country": (team.get("location") or "").lower()})
            summary = ((comp.get("status") or {}).get("summary") or status.get("detail") or "")
            state = status.get("state")
            # ESPN marks a match "Live" before the first ball ("Starts at 10:00
            # local time") - that is still to come, not live.
            if state == "in" and summary.lower().startswith("starts at"):
                state = "pre"
            yield {"league": league, "match": comp.get("description") or "", "start": start,
                   "state": state, "summary": summary, "sides": sides,
                   "top": bool(ev.get("isTopEvent"))}


def _line(e, now_utc=None) -> str:
    now_utc = now_utc or datetime.now(timezone.utc)
    teams = " v ".join(f"{s['name']} {s['score']}".strip() for s in e["sides"])
    where = ", ".join(x for x in (e["match"], e["league"]) if x)
    if e["state"] == "pre":
        # Past its start and still not begun - a delay, not "starts" at a time gone by.
        tail = (f"was due to start at {_when(e['start'])}, not started yet"
                if e["start"] < now_utc else f"starts {_when(e['start'])}")
    elif e["state"] == "in" and e["start"] < now_utc - timedelta(hours=20):
        tail = "multi-day match, still in progress" + (f" - {e['summary']}" if e["summary"] else "")
    else:
        tail = e["summary"]
    return f"- {teams}" + (f" ({where})" if where else "") + (f" - {tail}" if tail else "")


def _mentions(e, teams) -> bool:
    if not teams:
        return True
    blob = " ".join([e["league"]] + [s["name"].lower() + " " + s["country"] for s in e["sides"]]).lower()
    return all(t in blob for t in teams)


def _rank(e):
    names = " ".join(s["name"].lower() for s in e["sides"])
    international = any(n in names for n in _CRICKET_NATIONS)
    return (not e["top"], not international, e["start"])


async def _fetch(params=None) -> dict:
    async with httpx.AsyncClient(timeout=_TIMEOUT, headers={"User-Agent": "Mozilla/5.0"}) as client:
        resp = await client.get(_CRICKET_URL, params=params or {})
        resp.raise_for_status()
        return resp.json()


async def _day_answer(teams, day, now_utc):
    """Results (a past day) or the schedule (a coming day) for one date."""
    feed = await _fetch({"dates": day.strftime("%Y%m%d")})
    tz = _app_tz()
    on_day = [e for e in _events(feed) if _mentions(e, teams)
              and (e["start"].astimezone(tz).date() == day
                   or (e["state"] == "in" and e["start"].astimezone(tz).date() < day))]
    label = day.strftime("%A, %d %B %Y").replace(" 0", " ")
    who = f" for {' v '.join(t.title() for t in teams)}" if teams else ""
    stamp = f"From ESPN's scoreboard, fetched at {_when(now_utc)}."
    if not on_day:
        return (f"I couldn't find any cricket matches{who} on {label} on ESPN's scoreboard."
                f"\n\n{stamp}")
    past = day < now_utc.astimezone(tz).date()
    on_day.sort(key=_rank)
    head = f"**Cricket {'results' if past else 'matches'} for {label}**"
    lines = [head] + [_line(e, now_utc) for e in on_day[:_MAX_LINES]]
    if len(on_day) > _MAX_LINES:
        lines.append(f"- ...and {len(on_day) - _MAX_LINES} more")
    return "\n".join(lines) + f"\n\n{stamp}"


async def cricket_answer(teams=None, now_utc: datetime | None = None, day=None) -> dict:
    now_utc = now_utc or datetime.now(timezone.utc)
    teams = [t for t in (teams or []) if t]
    if day is not None:
        try:
            return {"available": True, "answer": await _day_answer(teams, day, now_utc),
                    "source": "ESPN"}
        except Exception as exc:
            logger.warning("[LiveSports] cricket results for %s failed: %s", day, exc)
            return {"available": False, "answer": (
                "I can't get cricket results for that day right now, so I won't guess. Please "
                "check ESPNcricinfo or Cricbuzz.")}
    try:
        feed = await _fetch()
    except Exception as exc:
        logger.warning("[LiveSports] cricket scoreboard failed: %s", exc)
        return {"available": False, "answer": (
            "I can't get live cricket scores right now, so I won't guess a score. Please check "
            "ESPNcricinfo or Cricbuzz for the latest.")}
    window_end = now_utc + timedelta(hours=24)
    events = [e for e in _events(feed) if _mentions(e, teams)]
    live = sorted((e for e in events if e["state"] == "in"), key=_rank)
    done = sorted((e for e in events if e["state"] == "post"
                   and e["start"] >= now_utc - timedelta(hours=30)), key=_rank)
    soon = sorted((e for e in events if e["state"] == "pre" and e["start"] <= window_end),
                  key=lambda e: (_rank(e)[0], _rank(e)[1], e["start"]))
    who = f" for {' v '.join(t.title() for t in teams)}" if teams else ""
    stamp = f"Scores from ESPN's live scoreboard, fetched at {_when(now_utc)}."
    if not (live or done or soon):
        return {"available": True, "answer": (
            f"There are no cricket matches{who} live, just finished or starting in the next 24 "
            f"hours on ESPN's scoreboard right now.\n\n{stamp}")}
    lines, shown = [], 0
    for title, group in (("**Live now**", live), ("**Finished recently**", done),
                         ("**Starting in the next 24 hours**", soon)):
        if not group or shown >= _MAX_LINES:
            continue
        take = group[:max(1, _MAX_LINES - shown)]
        lines.append(title)
        lines.extend(_line(e, now_utc) for e in take)
        if len(group) > len(take):
            lines.append(f"- ...and {len(group) - len(take)} more")
        lines.append("")
        shown += len(take)
    lines.append(stamp + " Live scores change ball by ball.")
    return {"available": True, "answer": "\n".join(lines).strip(), "observed_at": now_utc.isoformat(),
            "source": "ESPN"}


async def answer(req: dict) -> dict:
    return await cricket_answer(req.get("teams"), day=req.get("day"))
