"""services/live_requests.py

The request layer over services/live_info (QA sheet TP-001..082, Oct 16).

parse_request() reads everything a weather/time question can carry -
spelling, Hindi in Devanagari, units, date ranges, several cities, time-zone
questions, follow-up questions about the data just shown, and the trick
phrasings - and answer_request() answers it from the live sources. Every
figure is fetched; the model never supplies one.

What the sheet's first run found, and what each part here is for:
  * "what's the weather right now in Calgary?" read "right now in Calgary" as
    the place; "current wether in calgry", "temprature in delhii",
    "whats the wheather in mumbai rn" fell to web search (typos).
  * "दिल्ली का मौसम अभी कैसा है?" and "kal Jaipur mein baarish hogi kya?"
    fell to web search (Devanagari, "kal", "baarish").
  * weekend / 7-day / tonight / hourly / last week went to web search - the
    7-day answer was seven identical, invented rows.
  * °F / Kelvin / mph: "calgary temperature in kelvin" answered for Kelvin, BC.
  * "compare weather in calgary and toronto" read "calgary and toronto" as one
    place; "calgary, delhi and sydney" answered Calgary only.
  * time difference / "is calgary on MDT or MST?" came from search snapshots -
    one quoted a day-old "5:47 AM" as now.
  * "how old is this data?" / "where did you get this?" after a weather answer
    were answered by the model: "no timestamp", "from AccuWeather" - false.
  * "weather on Mars", "weather in 12345", "Ayush weather" (a Russian village),
    "show me yesterday's weather as today's", "from cache" (invented a cached
    snapshot), "pretend it is 13 October and ..." were all mishandled.
"""
import logging
import os
import re
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

import services.live_info as L
import services.live_markets as live_markets
import services.live_sports as live_sports

logger = logging.getLogger(__name__)

_WEATHER_WORD_TYPOS = {
    "wether": "weather", "wheather": "weather", "weathr": "weather", "wheater": "weather",
    "weahter": "weather", "waether": "weather", "weatehr": "weather", "wather": "weather",
    "temprature": "temperature", "tempreture": "temperature", "temperture": "temperature",
    "tempature": "temperature", "temparature": "temperature", "tempratur": "temperature",
    "temprture": "temperature", "temperatur": "temperature",
    "forcast": "forecast", "forecaste": "forecast", "forcaste": "forecast",
    "rn": "right now", "baarish": "rain", "barish": "rain", "baris": "rain",
}

# Hindi in Devanagari - the words a weather question needs, and the cities
# people ask about.
_DEVANAGARI = {
    "नई दिल्ली": "New Delhi", "दिल्ली": "Delhi", "मुंबई": "Mumbai", "जयपुर": "Jaipur",
    "कोलकाता": "Kolkata", "चेन्नई": "Chennai", "बेंगलुरु": "Bengaluru", "बैंगलोर": "Bangalore",
    "हैदराबाद": "Hyderabad", "पुणे": "Pune", "लखनऊ": "Lucknow", "नोएडा": "Noida",
    "गुरुग्राम": "Gurugram", "गुड़गांव": "Gurgaon", "अहमदाबाद": "Ahmedabad", "चंडीगढ़": "Chandigarh",
    "पटना": "Patna", "भोपाल": "Bhopal", "इंदौर": "Indore", "कैलगरी": "Calgary", "टोरंटो": "Toronto",
    "लंदन": "London", "दुबई": "Dubai", "सिंगापुर": "Singapore", "न्यूयॉर्क": "New York",
    "वैंकूवर": "Vancouver", "मौसम": "weather", "तापमान": "temperature", "बारिश": "rain",
    "अभी": "now", "आज": "today", "कल": "kal", "होगी": "hogi", "होगा": "hoga",
    "का": " ", "की": " ", "के": " ", "में": " ", "है": " ", "कैसा": " ", "कैसी": " ",
    "क्या": " ", "कितना": " ", "कितनी": " ", "बताओ": " ", "।": " ",
}

# Well-known cities, for a misspelt name the geocoder has no match for
# ("calgry", "delhii"). Only consulted after the geocoder found nothing.
_KNOWN_CITIES = (
    "Calgary", "Edmonton", "Toronto", "Vancouver", "Montreal", "Ottawa", "Winnipeg", "Victoria",
    "Halifax", "Regina", "Saskatoon", "Quebec City", "Delhi", "New Delhi", "Mumbai", "Bengaluru",
    "Bangalore", "Hyderabad", "Chennai", "Kolkata", "Pune", "Jaipur", "Ahmedabad", "Lucknow",
    "Noida", "Gurugram", "Gurgaon", "Chandigarh", "Indore", "Bhopal", "Patna", "Kochi", "Goa",
    "London", "Manchester", "Birmingham", "Edinburgh", "Dublin", "Paris", "Berlin", "Madrid",
    "Rome", "Amsterdam", "Zurich", "Vienna", "Lisbon", "New York", "Los Angeles", "Chicago",
    "Houston", "San Francisco", "Seattle", "Boston", "Miami", "Dallas", "Denver", "Washington",
    "Dubai", "Abu Dhabi", "Doha", "Riyadh", "Singapore", "Hong Kong", "Tokyo", "Seoul",
    "Beijing", "Shanghai", "Bangkok", "Kuala Lumpur", "Jakarta", "Manila", "Sydney",
    "Melbourne", "Brisbane", "Perth", "Auckland", "Johannesburg", "Cape Town", "Nairobi",
    "Cairo", "Istanbul", "Moscow", "Karachi", "Lahore", "Dhaka", "Kathmandu", "Colombo",
)

_UNITS_RE = re.compile(
    r"\s*\b(?:in|to)\s+(?P<u>fahrenheit|farenheit|°\s*f|deg(?:rees)?\s*f|celsius|centigrade|°\s*c|"
    r"kelvin|mph|miles\s+per\s+hour|km/?h|kph|kmph|f)\b\.?", re.IGNORECASE)
_TRICK_PREFIX_RE = re.compile(
    r"^\s*(?:please\s+)?(?:(?:don'?t|do\s+not|without)\s+(?:search(?:ing)?|google|looking\s+it\s+up)"
    r"[\s,;-]*(?:just\s+)?|just\s+)", re.IGNORECASE)
_PRETEND_RE = re.compile(r"\b(?:pretend|imagine|assume|say)\s+(?:that\s+)?(?:it(?:'s|\s+is)|today\s+is)\s+"
                         r"(?P<day>[^,]+?)\s*,?\s+and\s+", re.IGNORECASE)
_CACHE_RE = re.compile(r"\s+(?:from\s+(?:the\s+|your\s+)?(?:cache|memory)|cached|from\s+earlier)\b",
                       re.IGNORECASE)
_NOISE_TAIL_RE = re.compile(
    r"\s+(?:with\s+(?:the\s+)?(?:time\s+of\s+observation|observation\s+time|timestamp|time\s+stamp|"
    r"details?|time))\b|\s+for\s+(?:employees|staff|us|me|my\s+team|the\s+team|work|people|"
    r"the\s+office)\b", re.IGNORECASE)
_TELL_ME_RE = re.compile(r"^\s*(?:please\s+)?(?:tell|give|show|get)\s+(?:me\s+)?(?:the\s+)?(?=\S)",
                         re.IGNORECASE)
# "weather right now in Calgary": the time words stand between "weather" and
# the place, and were read as part of it (QA TP-002, TP-007).
_NOW_BEFORE_PLACE_RE = re.compile(r"\b(?:right\s+now|currently|at\s+the\s+moment|now|today)\s+(?=(?:in|at|for)\s)",
                                  re.IGNORECASE)
_MISLABEL_RE = re.compile(r"\b(?:as|like|labelled\s+as|instead\s+of)\s+(?:today'?s|current|now|live)\b",
                          re.IGNORECASE)
_PLANET_RE = re.compile(r"\b(?:on|in|at)\s+(?:the\s+)?(?P<body>mars|venus|jupiter|saturn|mercury|"
                        r"neptune|uranus|pluto|moon|sun)\b", re.IGNORECASE)
_FICTIONAL = {"atlantis", "narnia", "gotham", "wakanda", "hogwarts", "mordor", "middle earth",
              "el dorado", "neverland", "asgard", "westeros", "shangri-la", "shangri la", "oz"}
_POSTAL_RE = re.compile(r"\b(?:weather|temperature|forecast)\b.*\b(?:in|at|for)\s+(?P<code>\d{3,6})\b",
                        re.IGNORECASE)
# Places only the employee knows (QA TP-074: "what's the weather where I work"
# answered 'I couldn't recognise "where I work" as a place').
_UNKNOWN_LOCATION_RE = re.compile(
    r"\b(?:where\s+i\s+(?:work|am|live|stay)|my\s+(?:workplace|work\s*place|location|city|area|"
    r"town|home)|near\s+me|around\s+me|here)\b", re.IGNORECASE)
_WEATHERISH_RE = re.compile(rf"\b{L._WEATHER_WORD}\b|\bwind\s+speed\b|\bhot\b|\bcold\b", re.IGNORECASE)

# Ranges of days, and parts of a day.
_WEEKEND_RE = re.compile(r"\b(?:this\s+)?week[\s-]?end\b", re.IGNORECASE)
_N_DAYS_RE = re.compile(r"\b(?P<n>\d{1,2})[\s-]*days?\b|\bnext\s+(?P<m>\d{1,2})\s+days\b"
                        r"|\b(?P<w>(?:this|next)\s+week|week(?:ly)?\s+forecast)\b", re.IGNORECASE)
_LAST_WEEK_RE = re.compile(r"\b(?:last|past|previous)\s+(?:week|7\s+days|seven\s+days)\b", re.IGNORECASE)
_TONIGHT_RE = re.compile(r"\btonight\b|\bthis\s+(?:evening|night)\b|\baaj\s+raat\b", re.IGNORECASE)
_HOURLY_RE = re.compile(r"\bhourly\b|\bhour\s+by\s+hour\b|\bnext\s+(?:few|\d+)\s+hours\b", re.IGNORECASE)

# Time zones.
_PLACE_TXT = r"[a-z][a-z .'\-]{1,40}?"
_TIMEDIFF_RE = re.compile(
    rf"\b(?:time\s+)?difference\s+(?:in\s+time\s+)?between\s+(?P<a>{_PLACE_TXT})\s+and\s+"
    rf"(?P<b>{_PLACE_TXT})(?:\s+time)?\s*[?.!]*\s*$", re.IGNORECASE)
_TZINFO_RE = re.compile(
    rf"^\s*(?:is|does|which)\s+(?P<place>{_PLACE_TXT})\s+(?:on|in|observe|observes|use|uses|have|"
    rf"has|follow|follows)\s+(?:daylight\s+saving(?:s)?(?:\s+time)?|dst|[a-z]{{2,5}}\s+or\s+[a-z]{{2,5}}|"
    rf"[a-z]{{3,5}}|time\s*zone)(?:\s+time)?(?:\s+(?:right\s+)?now)?\s*[?.!]*\s*$"
    rf"|^\s*what(?:'s|\s+is)?\s+(?:the\s+)?time\s*zone\s+(?:of|in|for)\s+(?P<place2>{_PLACE_TXT})\s*[?.!]*\s*$"
    rf"|^\s*what\s+time\s*zone\s+is\s+(?P<place3>{_PLACE_TXT})\s+in\s*[?.!]*\s*$",
    re.IGNORECASE)
_TIMECONV_RE = re.compile(
    rf"\bwhat\s+time\s+(?:will\s+it\s+be|is\s+it|would\s+it\s+be)\s+in\s+(?P<place>{_PLACE_TXT})"
    r"(?:\s+on\s+(?P<date>[^?]+?))?\s+(?:at|when\s+it(?:'s|\s+is))\s+(?P<t>\d{1,2}(?::\d{2})?\s*(?:am|pm)?)"
    r"\s*(?:in\s+(?P<src_place>[a-z][a-z .'\-]{1,30}?)|(?P<src>[a-z]{2,5}))?\s*[?.!]*\s*$", re.IGNORECASE)
_TZ_BY_ABBR = {
    "IST": "Asia/Kolkata", "MST": "America/Edmonton", "MDT": "America/Edmonton",
    "EST": "America/Toronto", "EDT": "America/Toronto", "CST": "America/Chicago",
    "CDT": "America/Chicago", "PST": "America/Vancouver", "PDT": "America/Vancouver",
    "GMT": "Europe/London", "BST": "Europe/London", "UTC": "UTC", "CET": "Europe/Berlin",
    "CEST": "Europe/Berlin", "SGT": "Asia/Singapore", "GST": "Asia/Dubai", "JST": "Asia/Tokyo",
    "AEST": "Australia/Sydney", "AEDT": "Australia/Sydney", "HKT": "Asia/Hong_Kong",
}

# A follow-up asking about the weather just shown. Order matters: the first
# that matches names the question.
_META_RE = (
    ("source", re.compile(r"\bwhere\b.*\b(?:get|from|come)\b|\bsource\b|\bwhich\s+(?:site|website|"
                          r"service|api)\b|\bwho\s+(?:provides|gives)\b", re.IGNORECASE)),
    ("kind", re.compile(r"\blive\b.*\bforecast\b|\bforecast\b.*\blive\b|\breal[\s-]?time\b"
                        r"|\bobservation\b.*\bforecast\b", re.IGNORECASE)),
    ("sure", re.compile(r"\bare\s+you\s+sure\b|\bis\s+(?:this|it|that)\s+(?:really\s+)?(?:current|accurate|"
                        r"correct|right|up\s+to\s+date|up-to-date|live)\b|\bcan\s+i\s+trust\b", re.IGNORECASE)),
    ("age", re.compile(r"\bhow\s+old\b|\bhow\s+(?:recent|fresh)\b|\bage\s+of\b", re.IGNORECASE)),
    ("updated", re.compile(r"\b(?:last\s+)?updated?\b|\bwhen\s+(?:was|is)\s+(?:this|it|that)\b"
                           r"|\bobservation\s+time\b|\bobserved\b|\btimestamp\b", re.IGNORECASE)),
)

_DEFAULT_UNITS = {"temp": "C", "wind": "kmh"}

# NON_HR_LIVE_SOURCES: which parse_request() kinds are answered from a live
# source; the rest go to the model with web search. "all" (default), "none",
# or a comma list of: weather, time, sport, market, place.
_LIVE_SOURCE_GROUPS = {
    "weather": "weather", "special": "weather", "meta": "weather",
    "time": "time", "timediff": "time", "tzinfo": "time", "timeconv": "time",
    "sport": "sport", "market": "market", "place": "place",
}


def live_source_enabled(kind: str) -> bool:
    """Whether a request of this kind is answered from its live source rather
    than sent to web search. Read on every call so a config change needs no
    code change."""
    setting = os.getenv("NON_HR_LIVE_SOURCES", "all").strip().lower()
    if setting in ("", "all"):
        return True
    if setting == "none":
        return False
    enabled = {s.strip() for s in setting.split(",") if s.strip()}
    return _LIVE_SOURCE_GROUPS.get(kind, kind) in enabled


def _apply_word_maps(text: str) -> str:
    for hindi, word in sorted(_DEVANAGARI.items(), key=lambda kv: -len(kv[0])):
        text = text.replace(hindi, f" {word} ")

    def _fix(m):
        return _WEATHER_WORD_TYPOS.get(m.group(0).lower(), m.group(0))
    text = re.sub(r"\b[a-z]+\b", _fix, text, flags=re.IGNORECASE)
    # "kal" is yesterday or tomorrow; the verb says which.
    if re.search(r"\bkal\b", text, re.IGNORECASE):
        if re.search(r"\b(?:hogi|hoga|hoge|rahega|rahegi|will|hogaa)\b", text, re.IGNORECASE):
            text = re.sub(r"\bkal\b", "tomorrow", text, flags=re.IGNORECASE)
        elif re.search(r"\b(?:thi|tha|hui|hua|was)\b", text, re.IGNORECASE):
            text = re.sub(r"\bkal\b", "yesterday", text, flags=re.IGNORECASE)
    return re.sub(r"\s+", " ", text).strip()


def _units_of(text: str):
    """(text without the unit phrase, {"temp": C|F|K, "wind": kmh|mph})."""
    units = dict(_DEFAULT_UNITS)
    m = _UNITS_RE.search(text)
    if not m:
        return text, units
    u = re.sub(r"[\s°]", "", m.group("u").lower())
    if u in ("fahrenheit", "farenheit", "f", "degf", "degreesf"):
        units["temp"] = "F"
    elif u == "kelvin":
        units["temp"] = "K"
    elif u in ("mph", "milesperhour"):
        units["wind"] = "mph"
    return _cut(text, m), units


def _cut(text, m):
    return re.sub(r"\s+", " ", text[:m.start()] + " " + text[m.end():]).strip()


def _span_of(text: str, today):
    """(text without the range phrase, span) - span is None, ("range", start,
    end), ("tonight",) or ("hourly",)."""
    m = _WEEKEND_RE.search(text)
    if m:
        wd = today.weekday()                       # Mon=0 .. Sun=6
        if wd == 6:
            return _cut(text, m), ("range", today, today)
        sat = today + timedelta(days=5 - wd) if wd <= 5 else today
        return _cut(text, m), ("range", max(sat, today), sat + timedelta(days=1))
    m = _LAST_WEEK_RE.search(text)
    if m:
        return _cut(text, m), ("range", today - timedelta(days=7), today - timedelta(days=1))
    m = _N_DAYS_RE.search(text)
    if m and re.search(r"\b(?:forecast|weather|day|days|week)\b", text, re.IGNORECASE):
        n = int(m.group("n") or m.group("m") or 7)
        n = max(1, min(n, L.FORECAST_DAYS_AHEAD + 1))
        return _cut(text, m), ("range", today, today + timedelta(days=n - 1))
    m = _TONIGHT_RE.search(text)
    if m:
        return _cut(text, m), ("tonight",)
    m = _HOURLY_RE.search(text)
    if m:
        return _cut(text, m), ("hourly",)
    return text, None


def _split_places(place: str):
    """"calgary and toronto" / "calgary, delhi and sydney" / "calgary vs
    toronto" -> several places; "calgary, alberta" stays one."""
    parts = re.split(r"\s+(?:and|vs\.?|versus|&)\s+", place or "", flags=re.IGNORECASE)
    if len(parts) == 1:
        return [place]
    out = []
    for part in parts[:-1]:
        out.extend(p.strip() for p in part.split(",") if p.strip())
    out.append(parts[-1].strip())
    return [p for p in (L._clean_place(x) for x in out) if p][:5]


def _previous_live_place(context, today):
    for i in range(len(context) - 1, -1, -1):
        if context[i].get("role") == "user":
            earlier = parse_request(context[i].get("content") or "", context[:i], today)
            if earlier and earlier.get("place"):
                return earlier["place"]
    return None


def _last_was_live(context) -> bool:
    last = next((m.get("content") or "" for m in reversed(context or [])
                 if m.get("role") == "assistant"), "")
    return any(last.startswith(m) or m in last[:80] for m in L._LIVE_ANSWER_MARKERS)


def parse_request(query: str, context=None, today=None):
    """A dict with "kind" in weather / time / timediff / tzinfo / timeconv /
    meta / special, or None (not a live question)."""
    today = today or datetime.now(timezone.utc).date()
    raw = (query or "").strip().replace("’", "'")
    if not raw or L._HR_WORDS_RE.search(raw):
        return None
    # A crypto price or an exchange rate - first, so that after a weather
    # answer "bitcoin price right now" is not read as a city to look up
    # (live, Oct 16: 'I couldn't recognise "bitcoin price" as a place').
    market = live_markets.parse(raw) or live_markets.parse_followup(raw, context)
    if market:
        return {"kind": "market", "market": market}
    sport = live_sports.parse(raw)
    if sport:
        return {"kind": "sport", "sport": sport}
    context = context or []
    text = L._fold_day_typos(_apply_word_maps(raw))
    notice = None
    pretend_day = None
    pretend = _PRETEND_RE.search(text)
    if pretend:
        # "pretend it is 13 October and tell me calgary weather now": the
        # weather FOR that day - recorded if it has passed, a forecast if it is
        # coming - labelled with its own date, never presented as today's.
        pretend_day = L._resolve_day(pretend.group("day"), today)
        text = _PRETEND_RE.sub("", text)
        if pretend_day is None:
            notice = (f"I couldn't tell which date \"{pretend.group('day').strip()}\" is (try "
                      f"\"13 October\"), so this is the real weather right now:")
        elif pretend_day != today:
            when = L._fmt_day(datetime(pretend_day.year, pretend_day.month, pretend_day.day))
            now_label = L._fmt_day(datetime(today.year, today.month, today.day))
            notice = (f"Here is the weather for {when}, as you asked - shown as that day's "
                      f"{'recorded' if pretend_day < today else 'forecast'} weather, not as "
                      f"today's (today is {now_label}):")
    if _CACHE_RE.search(text):
        notice = "I don't serve cached weather - this is a fresh reading, fetched just now:"
        text = _CACHE_RE.sub("", text)
    text = _TELL_ME_RE.sub("", _TRICK_PREFIX_RE.sub("", text))
    text = _NOISE_TAIL_RE.sub("", _NOW_BEFORE_PLACE_RE.sub("", text))
    text, units = _units_of(text)

    m = _TIMEDIFF_RE.search(text)
    if m:
        return {"kind": "timediff", "places": [m.group("a").strip(), m.group("b").strip()]}
    m = _TIMECONV_RE.search(text)
    if m:
        return {"kind": "timeconv", "place": m.group("place").strip(), "date_text": m.group("date"),
                "time_text": m.group("t"), "src": (m.group("src") or "").upper() or None,
                "src_place": m.group("src_place")}
    m = _TZINFO_RE.search(text)
    if m:
        place = L._clean_place(m.group("place") or m.group("place2") or m.group("place3"))
        if place:
            return {"kind": "tzinfo", "place": place}

    if _WEATHERISH_RE.search(text):
        body = _PLANET_RE.search(text)
        if body:
            return {"kind": "special", "special": "planet", "body": body.group("body").lower()}
        code = _POSTAL_RE.search(text)
        if code:
            return {"kind": "special", "special": "postal", "code": code.group("code")}
        if _MISLABEL_RE.search(text) and re.search(r"\byesterday|tomorrow|\blast\b", text, re.IGNORECASE):
            return {"kind": "special", "special": "mislabel"}
        if _UNKNOWN_LOCATION_RE.search(text):
            return {"kind": "special", "special": "unknown_location"}

    # A question about the weather just shown ("how old is this data?") -
    # before parse(), which would read some of them as a new question.
    if _last_was_live(context):
        names_a_place = (L.parse(text, None, today) or {}).get("place")
        meta = next((name for name, pattern in _META_RE if pattern.search(text)), None)
        if meta and not names_a_place:
            place = _previous_live_place(context, today)
            if place:
                return {"kind": "meta", "meta": meta, "place": place}

    text = re.sub(r"\bwind\s+speed\b", "wind", text, flags=re.IGNORECASE)
    text, span = _span_of(text, today)
    if span and not re.search(rf"\b{L._WEATHER_WORD}\b", text, re.IGNORECASE):
        text = f"{text} weather"
    base = L.parse(text, context, today)
    if base is None and units != _DEFAULT_UNITS and _last_was_live(context):
        # "in Fahrenheit please" - the units change, the place does not.
        place = _previous_live_place(context, today)
        if place:
            base = {"kind": "weather", "place": place, "day": None, "day_text": None}
    if base is None:
        return None
    req = dict(base)
    req.update({"units": units, "span": span if req["kind"] == "weather" else None,
                "notice": notice})
    if pretend_day is not None and pretend_day != today and req["kind"] == "weather":
        # The pretended day wins over the "now" in the same sentence.
        req.update({"day": pretend_day, "span": None})
    if req["kind"] == "weather" and req.get("place"):
        places = _split_places(req["place"])
        if len(places) > 1:
            req["places"] = places
        if req["place"].lower() in _FICTIONAL:
            req.update({"kind": "special", "special": "fictional"})
    return req


# -- Answering --------------------------------------------------------------------

def _deg(value) -> str:
    """A whole-degree figure; never "-0"."""
    n = int(round(value))
    return str(0 if n == 0 else n)


def _convert_units(text: str, units) -> str:
    """The finished answer in the units asked for - the fetched figures,
    converted, never re-estimated."""
    if not units:
        return text
    if units.get("temp") in ("F", "K"):
        def _t(m):
            c, decimals = float(m.group(1)), "." in m.group(1)
            if units["temp"] == "F":
                v = c * 9 / 5 + 32
                return f"{v:.1f} °F" if decimals else f"{v:.0f} °F"
            v = c + 273.15
            return f"{v:.1f} K" if decimals else f"{v:.0f} K"
        text = re.sub(r"(-?\d+(?:\.\d+)?) °C", _t, text)
    if units.get("wind") == "mph":
        text = re.sub(r"(\d+(?:\.\d+)?) km/h", lambda m: f"{float(m.group(1)) * 0.621371:.0f} mph", text)
    return text


# Provinces, states and countries a city is commonly followed by - for a
# misspelt region ("Clagary ALberat").
_KNOWN_REGIONS = (
    "Alberta", "British Columbia", "Ontario", "Quebec", "Manitoba", "Saskatchewan", "Nova Scotia",
    "New Brunswick", "Newfoundland", "Prince Edward Island", "Yukon", "Nunavut",
    "California", "Texas", "Florida", "New York", "Washington", "Illinois", "Massachusetts",
    "Missouri", "Colorado", "Arizona", "Georgia", "Ohio", "Michigan", "Pennsylvania", "Oregon",
    "Nevada", "Virginia", "New Jersey", "North Carolina", "Minnesota", "Tennessee",
    "Maharashtra", "Karnataka", "Telangana", "Tamil Nadu", "Kerala", "Gujarat", "Rajasthan",
    "Uttar Pradesh", "West Bengal", "Punjab", "Haryana", "Madhya Pradesh", "Bihar", "Delhi",
    "England", "Scotland", "Wales", "Canada", "India", "United States", "United Kingdom",
    "Australia", "Germany", "France", "Spain", "Italy", "Netherlands", "Switzerland", "Ireland",
    "United Arab Emirates", "Singapore", "Japan", "China", "Pakistan", "Bangladesh", "Nepal",
    "Sri Lanka", "South Africa", "New Zealand", "Mexico", "Brazil", "Canada",
)


def _closest(text: str, choices, cutoff: float):
    import difflib
    lowered = {c.lower(): c for c in choices}
    hit = difflib.get_close_matches(text.lower(), list(lowered), n=1, cutoff=cutoff)
    return lowered[hit[0]] if hit else None


def _correct_place(place: str):
    """The well-known place a misspelt name means, region kept: "calgry" ->
    "Calgary", "Clagary ALberta" -> "Calgary, Alberta", "torotno ontaria" ->
    "Toronto, Ontario" - or None. QA (Oct 16): "what is the temperature in
    Clagary ALberta" got 'I couldn't recognise "Clagary ALberta"' - only a
    misspelt WHOLE name was corrected, never a city followed by its region."""
    words = [w for w in re.split(r"[,\s]+", place or "") if w]
    for k in range(min(3, len(words)), 0, -1):
        city = _closest(" ".join(words[:k]), _KNOWN_CITIES, 0.78)
        if not city:
            continue
        rest, region = words[k:], []
        i = 0
        while i < len(rest):
            two = " ".join(rest[i:i + 2]) if i + 1 < len(rest) else None
            match = (_closest(two, _KNOWN_REGIONS, 0.8) if two else None)
            if match:
                region.append(match)
                i += 2
                continue
            region.append(_closest(rest[i], _KNOWN_REGIONS, 0.8) or rest[i])
            i += 1
        return ", ".join([city] + region)
    return None


async def _geocode_with_typos(place: str):
    """The geocoder's match - or, when it has none (or only a tiny place), the
    well-known place a misspelt name means. (geo, corrected name or None)."""
    geo = await L._geocode(place)
    if geo and (geo.get("alternatives") or (geo.get("population") or 0) >= SMALL_PLACE_POPULATION
                or "," in place):
        return geo, None
    corrected = _correct_place(place)
    if corrected and corrected.lower().replace(",", "") != (place or "").lower().replace(",", ""):
        better = await L._geocode(corrected)
        if better:
            return better, corrected
    return geo, None


async def _range_answer(geo, start, end, local_today):
    label = L._place_label(geo)
    if (start - local_today).days > L.FORECAST_DAYS_AHEAD:
        return (f"Weather forecasts only go up to {L.FORECAST_DAYS_AHEAD} days ahead, so I can't give "
                f"a reliable forecast for {label} for those dates yet.")
    end = min(end, local_today + timedelta(days=L.FORECAST_DAYS_AHEAD))
    past = end < local_today
    daily = ("weather_code,temperature_2m_max,temperature_2m_min,precipitation_sum,wind_speed_10m_max"
             + ("" if past else ",precipitation_probability_max"))
    url = L._ARCHIVE_URL if (local_today - start).days > L.RECENT_PAST_DAYS else None
    data = await L._fetch_weather({"latitude": geo["latitude"], "longitude": geo["longitude"],
                                   "timezone": geo.get("timezone") or "auto", "daily": daily,
                                   "start_date": start.isoformat(), "end_date": end.isoformat()}, url)
    d = data.get("daily") or {}
    days = d.get("time") or []
    if not days:
        raise ValueError("no daily values")
    span = (f"{L._fmt_day(datetime(start.year, start.month, start.day))} to "
            f"{L._fmt_day(datetime(end.year, end.month, end.day))}")
    head = (f"**Recorded weather for {label}, {span}:**" if past else
            f"**Forecast for {label}, {span}** (a forecast - it can still change):")
    lines = [head]
    for i, day in enumerate(days):
        dt = datetime.fromisoformat(day)

        def get(k, i=i):
            values = d.get(k) or []
            return values[i] if i < len(values) else None
        part = (f"- {dt.strftime('%a %d %b').replace(' 0', ' ')}: high "
                f"{_deg(get('temperature_2m_max'))} °C, low {_deg(get('temperature_2m_min'))} °C")
        sky = L._WEATHER_CODES.get(get("weather_code"))
        if sky:
            part += f", {sky.lower()}"
        if get("precipitation_probability_max") is not None and not past:
            part += f", {get('precipitation_probability_max'):.0f}% chance of precipitation"
        elif get("precipitation_sum") is not None:
            part += f", {get('precipitation_sum'):.1f} mm precipitation"
        lines.append(part)
    return "\n".join(lines)


async def _hours_answer(geo, now_utc, tonight: bool):
    tz = ZoneInfo(geo.get("timezone") or "UTC")
    now_local = now_utc.astimezone(tz)
    data = await L._fetch_weather({"latitude": geo["latitude"], "longitude": geo["longitude"],
                                   "timezone": geo.get("timezone") or "auto", "forecast_days": 2,
                                   "hourly": "temperature_2m,weather_code,precipitation_probability"})
    h = data.get("hourly") or {}
    rows = []
    for i, t in enumerate(h.get("time") or []):
        dt = datetime.fromisoformat(t).replace(tzinfo=tz)
        pick = lambda k: (h.get(k) or [None] * (i + 1))[i] if i < len(h.get(k) or []) else None
        rows.append((dt, pick("temperature_2m"), pick("weather_code"), pick("precipitation_probability")))
    label = L._place_label(geo)
    if tonight:
        start = now_local.replace(hour=18, minute=0, second=0, microsecond=0)
        if now_local.hour < 6:
            start -= timedelta(days=1)
        end = start + timedelta(hours=12)
        part = [r for r in rows if start <= r[0] < end and r[0] >= now_local - timedelta(hours=1)]
        if not part:
            raise ValueError("no hours for tonight")
        temps = [r[1] for r in part if r[1] is not None]
        skies = [L._WEATHER_CODES.get(r[2]) for r in part if r[2] is not None]
        sky = max(set(skies), key=skies.count) if skies else None
        pop = max((r[3] for r in part if r[3] is not None), default=None)
        return (f"**Tonight in {label}** (a forecast, {L._fmt_time(start)} to {L._fmt_time(end)} "
                f"{L._abbr(start)}):\n- Low {_deg(min(temps))} °C, high {_deg(max(temps))} °C"
                + (f"\n- Mostly {sky.lower()}" if sky else "")
                + ((f"\n- Up to {pop:.0f}% chance of precipitation" if pop else
                    "\n- No precipitation expected") if pop is not None else ""))
    upcoming = [r for r in rows if r[0] >= now_local.replace(minute=0, second=0, microsecond=0)][:12]
    if not upcoming:
        raise ValueError("no upcoming hours")
    lines = [f"**Hourly forecast for {label}** (a forecast, local time {L._abbr(upcoming[0][0])}):"]
    for dt, temp, code, pop in upcoming:
        sky = L._WEATHER_CODES.get(code)
        lines.append(f"- {L._fmt_time(dt)}: {_deg(temp)} °C" + (f", {sky.lower()}" if sky else "")
                     + (f", {pop:.0f}% chance of precipitation" if pop is not None else ""))
    return "\n".join(lines)


async def _one_place_weather(place, req, now_utc):
    span, day = req.get("span"), req.get("day")
    try:
        geo, corrected = await _geocode_with_typos(place)
    except Exception:
        return f"I can't get the weather for {place} right now, so I won't guess."
    note = f"(I read \"{place}\" as {corrected}.)\n\n" if corrected else ""
    if corrected:
        place = corrected
    if span is None:
        text = (await L.weather_answer(place, now_utc=now_utc, day=day))["answer"]
    elif not geo:
        text = L._ask_for_city("weather", place)
    elif geo.get("alternatives"):
        text = L._which_place_answer("weather", place, geo["alternatives"])
    else:
        local_today = now_utc.astimezone(ZoneInfo(geo.get("timezone") or "UTC")).date()
        try:
            if span[0] == "range":
                text = await _range_answer(geo, span[1], span[2], local_today)
            else:
                text = await _hours_answer(geo, now_utc, tonight=span[0] == "tonight")
        except Exception as exc:
            logger.warning("[LiveRequests] %s lookup failed for %r: %s", span[0], place, exc)
            text = f"I can't get that forecast for {L._place_label(geo)} right now, so I won't guess."
    return note + text if geo else text


#: Below this population (or with none recorded), a place named on its own is
#: confirmed before answering - see _small_place_check.
SMALL_PLACE_POPULATION = int(os.getenv("LIVE_SMALL_PLACE_POPULATION", "5000"))


async def _small_place_check(place):
    """A place nobody would mean from its name alone - a village - is
    confirmed first. QA TP-075: "Ayush weather" answered for a village in
    Russia."""
    if "," in place or len(place.split()) > 1:
        return None
    # A misspelt well-known city ("delih" -> Delhi) is corrected, not confirmed:
    # the geocoder's only "delih" is a village in Türkiye.
    if _correct_place(place) and _correct_place(place).lower() != place.lower():
        return None
    try:
        geo = await L._geocode(place)
    except Exception:
        return None
    if not geo or geo.get("alternatives") or L._is_country(geo):
        return None
    if (geo.get("population") or 0) >= SMALL_PLACE_POPULATION:
        return None
    country = geo.get("country") or L._COUNTRY_CODE_NAMES.get(str(geo.get("country_code") or ""), "")
    return (f"{L._ASKED_FOR_CITY}? The only place I found called \"{place}\" is a small one - "
            f"{L._place_label(geo)}. If that's it, ask \"weather in {geo.get('name')}, {country}\"; "
            f"otherwise tell me the city and country you meant.")


def _offset_text(minutes: int) -> str:
    h, m = divmod(abs(minutes), 60)
    return f"{h} hour{'s' if h != 1 else ''}" + (f" {m} minutes" if m else "")


def _next_transition(tz: ZoneInfo, now_utc: datetime):
    """The next moment `tz` changes its UTC offset (a DST change) within a
    year, or None."""
    current = now_utc.astimezone(tz).utcoffset()
    step = now_utc
    for _ in range(366):
        nxt = step + timedelta(days=1)
        if nxt.astimezone(tz).utcoffset() != current:
            lo, hi = step, nxt
            while hi - lo > timedelta(minutes=1):
                mid = lo + (hi - lo) / 2
                if mid.astimezone(tz).utcoffset() == current:
                    lo = mid
                else:
                    hi = mid
            return hi
        step = nxt
    return None


async def _geo_for_time(place):
    geo, _ = await _geocode_with_typos(place)
    return geo if geo and geo.get("timezone") else None


async def _timediff_answer(a, b, now_utc):
    geos = []
    for place in (a, b):
        geo = await _geo_for_time(place)
        if not geo:
            return L._ask_for_city("time", place)
        geos.append(geo)
    tz_a, tz_b = ZoneInfo(geos[0]["timezone"]), ZoneInfo(geos[1]["timezone"])
    la, lb = now_utc.astimezone(tz_a), now_utc.astimezone(tz_b)
    diff = int((la.utcoffset() - lb.utcoffset()).total_seconds() // 60)
    na, nb = geos[0].get("name"), geos[1].get("name")
    if diff == 0:
        line = f"{na} and {nb} are on the same time right now ({L._tz_label(la)})."
    else:
        rel = "behind" if diff < 0 else "ahead of"
        line = (f"{na} is {_offset_text(diff)} {rel} {nb} right now - {L._fmt_time(la)} {L._abbr(la)} "
                f"in {na}, {L._fmt_time(lb)} {L._abbr(lb)} in {nb}.")
    changes = []
    for tz, name in ((tz_a, na), (tz_b, nb)):
        when = _next_transition(tz, now_utc)
        if when:
            after = when + timedelta(hours=1)
            new_diff = int((after.astimezone(tz_a).utcoffset()
                            - after.astimezone(tz_b).utcoffset()).total_seconds() // 60)
            changes.append(f"{name} changes to {L._abbr(after.astimezone(tz))} on "
                           f"{L._fmt_day(when.astimezone(tz))}; after that the difference is "
                           f"{_offset_text(new_diff)}.")
    return line + ((" " + " ".join(changes)) if changes else "")


async def _tzinfo_answer(place, now_utc):
    geo = await _geo_for_time(place)
    if not geo:
        return L._ask_for_city("time", place)
    tz = ZoneInfo(geo["timezone"])
    local = now_utc.astimezone(tz)
    text = (f"{L._place_label(geo)} is on {L._abbr(local)} ({L._tz_label(local)}) right now - "
            f"it's {L._fmt_time(local)} on {L._fmt_day(local)} there.")
    when = _next_transition(tz, now_utc)
    if when:
        after = (when + timedelta(hours=1)).astimezone(tz)
        ends = bool(local.dst())
        text += (f" It switches to {L._abbr(after)} ({L._tz_label(after)}) on "
                 f"{L._fmt_day(when.astimezone(tz))}, when daylight saving time "
                 f"{'ends' if ends else 'starts'}.")
    else:
        text += " It doesn't change its clocks for daylight saving time."
    return text


async def _timeconv_answer(req, now_utc, today):
    geo = await _geo_for_time(req["place"])
    if not geo:
        return L._ask_for_city("time", req["place"])
    if req.get("src") in _TZ_BY_ABBR:
        src_tz = ZoneInfo(_TZ_BY_ABBR[req["src"]])
    elif req.get("src_place"):
        src_geo = await _geo_for_time(req["src_place"])
        if not src_geo:
            return L._ask_for_city("time", req["src_place"])
        src_tz = ZoneInfo(src_geo["timezone"])
    else:
        src_tz = ZoneInfo(os.getenv("QUOTA_TIMEZONE", "UTC"))
    m = re.match(r"(\d{1,2})(?::(\d{2}))?\s*(am|pm)?", req["time_text"].strip(), re.IGNORECASE)
    hour, minute, ampm = int(m.group(1)), int(m.group(2) or 0), (m.group(3) or "").lower()
    if ampm == "pm" and hour != 12:
        hour += 12
    if ampm == "am" and hour == 12:
        hour = 0
    day = L._resolve_day(req["date_text"], today) if req.get("date_text") else today
    if day is None:
        return "I couldn't read that date - could you give it like \"2 November 2026\"?"
    src_dt = datetime(day.year, day.month, day.day, hour, minute, tzinfo=src_tz)
    dst = src_dt.astimezone(ZoneInfo(geo["timezone"]))
    return (f"{L._fmt_time(src_dt)} {L._abbr(src_dt)} on {L._fmt_day(src_dt)} is "
            f"{L._fmt_time(dst)} {L._abbr(dst)} on {L._fmt_day(dst)} in {L._place_label(geo)} "
            f"({L._tz_label(dst)}).")


async def _meta_answer(req, now_utc):
    result = await L.weather_answer(req["place"], now_utc=now_utc)
    observed = result.get("observed_at")
    if not result.get("available") or not observed:
        return ("I can't reach the weather service right now to check, so I can't confirm how "
                "current that reading is.")
    valid_at = datetime.fromisoformat(observed)
    # The place's own zone, so the time reads "12:15 AM MDT", not "UTC-06:00".
    try:
        geo = await L._geocode(req["place"])
        if geo and geo.get("timezone"):
            valid_at = valid_at.astimezone(ZoneInfo(geo["timezone"]))
    except Exception:
        pass
    minutes = max(0, int((now_utc - valid_at.astimezone(timezone.utc)).total_seconds() // 60))
    when = f"{L._fmt_time(valid_at)} {L._abbr(valid_at)} on {L._fmt_day(valid_at)}"
    age = (f"{minutes} minute{'s' if minutes != 1 else ''} ago" if minutes < 120
           else f"about {minutes // 60} hours ago")
    fresh = not result.get("stale")
    name = req["meta"]
    if name == "source":
        return (f"It comes from {L.SOURCE_NAME}, a weather service built on national weather "
                f"services' data - fetched live when you asked, not from a web search. The "
                f"reading is for {when} ({age}).")
    if name == "kind":
        return (f"The \"Current weather\" figures are live conditions for {when} ({age}) - a "
                f"model analysis from weather-service data, refreshed every 15 minutes, not a "
                f"single weather-station reading. The \"Forecast for today\" high and low are a "
                f"forecast.")
    if name == "sure":
        return ((f"Yes - I fetched it live just now. The reading is for {when}, {age}; the "
                 f"service refreshes it every 15 minutes.") if fresh else
                (f"No - the latest reading I can get is from {when}, {age}, so it may not "
                 f"reflect conditions right now."))
    return (f"The reading is for {when} - {age}. The service refreshes current conditions "
            f"every 15 minutes" + ("." if fresh else ", but this one is out of date."))


async def answer_request(req: dict, now_utc: datetime | None = None) -> dict:
    """{"answer": text, "available": bool} for a parse_request() dict."""
    now_utc = now_utc or datetime.now(timezone.utc)
    today = now_utc.astimezone(ZoneInfo(os.getenv("QUOTA_TIMEZONE", "UTC"))).date()
    kind = req.get("kind")
    if kind == "market":
        return await live_markets.answer(req["market"])
    if kind == "sport":
        return await live_sports.answer(req["sport"])
    try:
        if kind == "timediff":
            return {"answer": await _timediff_answer(*req["places"], now_utc), "available": True}
        if kind == "tzinfo":
            return {"answer": await _tzinfo_answer(req["place"], now_utc), "available": True}
        if kind == "timeconv":
            return {"answer": await _timeconv_answer(req, now_utc, today), "available": True}
        if kind == "meta":
            return {"answer": await _meta_answer(req, now_utc), "available": True}
    except Exception as exc:
        logger.warning("[LiveRequests] %s failed: %s", kind, exc)
        return {"answer": "I can't look that up right now, so I won't guess - please try again "
                          "in a moment.", "available": False}
    if kind == "special":
        special = req["special"]
        if special == "planet":
            body = "the Moon" if req["body"] == "moon" else ("the Sun" if req["body"] == "sun"
                                                             else req["body"].title())
            return {"available": False, "answer": (
                f"I can only give the weather for places on Earth - there's no live weather "
                f"service for {body}. Tell me a city and I'll get its weather.")}
        if special == "postal":
            return {"available": False, "answer": (
                f"{L._ASKED_FOR_CITY}? I can't reliably look up weather by a postal code like "
                f"{req['code']} - please tell me the city and country.")}
        if special == "fictional":
            name = req["place"].title()
            return {"available": False, "answer": (
                f"{name} is a legendary place, so it has no weather. If you meant a real town "
                f"called {name}, add the country (e.g. \"weather in {name}, South Africa\").")}
        if special == "unknown_location":
            return {"available": False, "answer": (
                f"{L._ASKED_FOR_CITY}? I don't know where you work or where you are - tell me the "
                f"city and country (e.g. \"weather in Calgary, Canada\").")}
        return {"available": False, "answer": (
            "I can't show yesterday's weather as today's - they're different readings, and "
            "labelling one as the other would be wrong. Tell me the city and I'll show "
            "yesterday's recorded weather and today's current weather, each clearly labelled.")}
    if kind == "time":
        place = req.get("place")
        if place:
            geo, corrected = await _geocode_with_typos(place)
            if corrected:
                place = corrected
        return await L.time_answer(place, now_utc=now_utc)
    places = req.get("places") or [req.get("place")]
    if not any(places):
        # No city named ("what is the weather today") - ask for one.
        return await L.weather_answer(None, now_utc=now_utc)
    if (len(places) == 1 and places[0] and req.get("span") is None and not req.get("day")
            and not req.get("notice")):
        small = await _small_place_check(places[0])
        if small:
            return {"answer": small, "available": False}
    if len(places) == 1 and req.get("span") is None:
        # One place: keep the reading's own details (observed_at, stale) for
        # the response data, as live_info.weather_answer gives them.
        place = places[0]
        try:
            _, corrected = await _geocode_with_typos(place)
        except Exception:
            corrected = None
        result = dict(await L.weather_answer(corrected or place, now_utc=now_utc, day=req.get("day")))
        text = _convert_units(result["answer"], req.get("units"))
        if corrected and result.get("available"):
            text = f"(I read \"{place}\" as {corrected}.)\n\n{text}"
        result["answer"] = f"{req['notice']}\n\n{text}" if req.get("notice") else text
        return result
    parts = [await _one_place_weather(place, req, now_utc) for place in places]
    text = _convert_units("\n\n".join(parts), req.get("units"))
    if req.get("notice"):
        text = f"{req['notice']}\n\n{text}"
    return {"answer": text, "available": True}
