"""services/live_info.py

Questions whose answer is only right if it is LIVE - the weather now, and
what time it is somewhere - answered from a live source with the reading's
own timestamp, never from a web-search snippet or the model's memory.

Why (P1, Oct 14): "current weather in calgary" at 12:18 PM MDT was answered
"as of 5 PM MDT on 13 Oct" - 19 hours old - and presented as current. There
was no weather lookup at all: race-api's Brave search returned search-index
SNAPSHOTS of weather pages (no age, no date - just title, url, a snippet) and
the model repeated the observation time printed in one. Re-running it a day
later returned "Observed at: 8:00 PM MDT Wednesday 14 October" on the 15th:
a search index is always behind, so it can never be "current".

Time had the same flaw from another side: the model was only ever given the
app's own clock (QUOTA_TIMEZONE, Asia/Kolkata), so "what time is it in
Calgary" was the model converting from IST in its head.

Source: Open-Meteo (https://open-meteo.com) - free, keyless. Its geocoder
returns each place's IANA timezone (used for the time answer too), and its
"current" block is the latest model analysis (15-minute steps) built from the
national weather services' models, with the time it is valid for. It is a
model estimate, not a station observation, and the answer says so. If it
cannot be reached, the answer says it cannot get live weather - it never
falls back to search results or a guess.
"""
import logging
import os
import re
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

import httpx

logger = logging.getLogger(__name__)

_GEOCODE_URL = os.getenv("LIVE_GEOCODE_URL", "https://geocoding-api.open-meteo.com/v1/search")
_WEATHER_URL = os.getenv("LIVE_WEATHER_URL", "https://api.open-meteo.com/v1/forecast")
_TIMEOUT = float(os.getenv("LIVE_INFO_TIMEOUT_SECONDS", "6"))
#: A "current" reading older than this is said to be out of date, not current.
STALE_AFTER = timedelta(minutes=int(os.getenv("LIVE_WEATHER_STALE_MINUTES", "90")))

SOURCE_NAME = "Open-Meteo"

# -- Recognising the question --------------------------------------------------

_HR_WORDS_RE = re.compile(
    r"\b(?:shift|punch\w*|attendance|leave|leaves|office|login|log\s*in|check[\s-]?in|"
    r"check[\s-]?out|clock[\s-]?(?:in|out)|work(?:ing)?\s+hours?|time\s*sheet|timesheet|"
    r"time\s+off|overtime|late|regulari\w*|holiday|payroll|salary)\b", re.IGNORECASE)

_PLACE = r"(?P<place>[a-z][a-z .,'\-]{1,60}?)"
_TAIL = r"(?:\s+(?:right\s+)?(?:now|today|currently|at\s+the\s+moment|please|pls))*\s*[?.!]*\s*$"
_WEATHER_WORD = (r"(?:weather|temperature|temp|climate|humidity|wind|forecast|conditions|"
                 r"rain(?:ing)?|snow(?:ing)?)")

_WEATHER_RES = (
    # "current weather in calgary", "what is the temperature in delhi now"
    re.compile(rf"\b{_WEATHER_WORD}\b(?:\s+(?:will\s+)?(?:be|is|was)(?:\s+like)?)?"
               rf"(?:\s+(?:like|report|update|today|now|currently))?"
               rf"\s+(?:in|at|of|for|near)\s+{_PLACE}{_TAIL}", re.IGNORECASE),
    # "calgary weather", "delhi temperature today"
    re.compile(rf"^\s*(?:what(?:'s|\s+is)\s+(?:the\s+)?)?(?:current\s+|today'?s\s+|live\s+)?"
               rf"{_PLACE}\s+{_WEATHER_WORD}{_TAIL}", re.IGNORECASE),
    # "how hot is it in delhi", "is it raining in calgary"
    re.compile(rf"\b(?:how\s+(?:hot|cold|warm|windy|humid)|is\s+it\s+(?:raining|snowing|"
               rf"hot|cold|sunny|cloudy|windy))\b(?:\s+(?:it\s+is|is\s+it|outside))?"
               rf"\s+(?:in|at)\s+{_PLACE}{_TAIL}", re.IGNORECASE),
    # "weather calgary", "current temperature calgary" - the word first, then the
    # place. The place may not open with a verb or filler ("weather is nice").
    re.compile(rf"^\s*(?:(?:what(?:'s|\s+is)\s+)?(?:the\s+)?)?(?:current\s+|today'?s\s+|live\s+)?"
               rf"{_WEATHER_WORD}\s+(?!(?:is|was|are|were|will|has|have|be|looks?|like|report|"
               rf"update|today|tomorrow|now|in|at|of|for|near)\b){_PLACE}{_TAIL}", re.IGNORECASE),
)

_TIME_RES = (
    # "what time is it in calgary", "current time in delhi", "time in london now"
    re.compile(rf"\b(?:what(?:'s|\s+is)?\s+(?:the\s+)?(?:current\s+|local\s+|exact\s+)?time"
               rf"(?:\s+is\s+it|\s+now|\s+right\s+now)?|current\s+time|local\s+time|time\s+now|"
               rf"^\s*time)\s+(?:in|at|of)\s+{_PLACE}{_TAIL}", re.IGNORECASE),
    # "calgary time", "what's calgary time now"
    re.compile(rf"^\s*(?:what(?:'s|\s+is)\s+(?:the\s+)?)?(?:current\s+|local\s+)?{_PLACE}"
               rf"\s+(?:local\s+)?time{_TAIL}", re.IGNORECASE),
)
# No place: "weather", "what's the weather like", "current temperature".
_WEATHER_HERE_RE = re.compile(
    rf"^\s*(?:(?:please\s+)?(?:(?:tell|show|give)(?:\s+me)?\s+)?(?:what(?:'s|\s+is)\s+|how(?:'s|\s+is)\s+)?"
    rf"(?:the\s+)?(?:current\s+|today'?s\s+|live\s+)?{_WEATHER_WORD}(?:\s+like)?(?:\s+(?:outside|today|now|update))*"
    rf"|is\s+it\s+(?:raining|snowing)(?:\s+outside)?)\s*[?.!]*\s*$", re.IGNORECASE)
# No place: "what time is it", "current time", "time now".
_TIME_HERE_RE = re.compile(
    r"^\s*(?:(?:please\s+)?(?:tell\s+me\s+)?(?:what(?:'s|\s+is)?\s+(?:the\s+)?"
    r"(?:current\s+|exact\s+)?time(?:\s+is\s+it)?|current\s+time|time\s+now|the\s+time))"
    r"(?:\s+(?:right\s+)?(?:now|please|pls))*\s*[?.!]*\s*$", re.IGNORECASE)

_NOT_A_PLACE = {"it", "there", "here", "the", "my", "your", "our", "this", "that", "today",
                "tomorrow", "now", "outside", "home", "office", "work", "current", "local",
                "exact", "what", "the current", "today's", "conditions", "forecast", "report",
                "update", "temperature", "weather", "like",
                # Chat after a live answer is not a city ("thanks" -> weather in Thanks).
                "thanks", "thank you", "thankyou", "thx", "ok", "okay", "cool", "nice", "great",
                "good", "yes", "no", "yeah", "nope", "sure", "hi", "hello", "hey", "bye", "done",
                "got it", "fine", "wow", "awesome", "perfect", "noted", "alright", "hmm", "k"}

# Trailing words that are not part of a place name: "calgary current", "delhi live".
_PLACE_FILLER_RE = re.compile(
    r"\s+(?:(?:right\s+)?now|today|currently|current|live|latest|outside|please|pls)\s*$",
    re.IGNORECASE)

# The live source only has the weather NOW (and today's high/low). A question
# about another day is not answered from it - it would present current
# conditions as if they were the day asked about.
_OTHER_DAY_RE = re.compile(
    r"\b(?:tomorrow|tonight|yesterday|day\s+after|next\s+\w+|this\s+week(?:end)?|weekend|"
    r"(?:mon|tues?|wednes|thurs?|fri|satur|sun)day|\d+[\s-]*days?|week(?:ly)?|"
    r"\d{1,2}(?:st|nd|rd|th)?\s+(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*|"
    r"(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?\s+\d{1,2}\b|"
    r"\d{4}-\d{2}-\d{2})\b", re.IGNORECASE)

# How people abbreviate a country; the geocoder spells it out ("United States").
_COUNTRY_ALIASES = {"usa": "united states", "u.s.a": "united states", "uk": "united kingdom",
                    "uae": "united arab emirates"}

# Day words typed wrong - "toaday", "tommorow", "yesturday", "tmrw". Live
# (Oct 15): "what is weather toaday" asked for weather in a place called
# "toaday". Folded to the real word before anything reads the message.
_DAY_WORDS = ("today", "tomorrow", "yesterday", "tonight")
_DAY_WORD_SHORTHAND = {"tmrw": "tomorrow", "tmr": "tomorrow", "tmrrw": "tomorrow",
                       "2moro": "tomorrow", "2mrw": "tomorrow", "2day": "today",
                       "tdy": "today", "tday": "today", "2nite": "tonight", "ystrdy": "yesterday"}


def _fold_day_typos(text: str) -> str:
    import difflib

    def _fix(m):
        word = m.group(0)
        lower = word.lower()
        if lower in _DAY_WORD_SHORTHAND:
            return _DAY_WORD_SHORTHAND[lower]
        if lower in _DAY_WORDS or not 4 <= len(lower) <= 10:
            return word
        close = difflib.get_close_matches(lower, _DAY_WORDS, n=1, cutoff=0.8)
        return close[0] if close else word
    return re.sub(r"\b[a-z0-9]+\b", _fix, text or "", flags=re.IGNORECASE)


def detect(query: str):
    """("weather", place) / ("time", place or None) for a live question, else
    None. Never for an HR question that happens to say "time" ("what time is
    my shift", "punch in time")."""
    text = _fold_day_typos((query or "").strip().replace("’", "'"))
    if not text or _HR_WORDS_RE.search(text):
        return None
    text = re.sub(r"\s+", " ", _HINGLISH_RE.sub(" ", text)).strip()
    # No place named, checked FIRST: the "<place> weather" shape otherwise
    # reads "what is temperature today" as weather in a place called "what is".
    if _WEATHER_HERE_RE.match(text):
        return "weather", None
    for pattern in (() if _OTHER_DAY_RE.search(text) else _WEATHER_RES):
        m = pattern.search(text)
        if m and _clean_place(m.group("place")):
            return "weather", _clean_place(m.group("place"))
    # Before the "<place> time" shape, which reads "current time" as a place.
    if _TIME_HERE_RE.match(text):
        return "time", None
    for pattern in _TIME_RES:
        m = pattern.search(text)
        if m and _clean_place(m.group("place")):
            return "time", _clean_place(m.group("place"))
    return None


# -- Dates, Hinglish and follow-ups ---------------------------------------------
#
# Live (Oct 15): "1 Nov 2026 ko Calgary weather" matched nothing above (a date
# and a Hindi particle in front of "<place> weather"), fell to the chat model,
# and came back in KOREAN - "ko" read as the language code. And after "Which
# city would you like the weather for?", the reply "noida" was answered as a
# fresh question (an encyclopedia entry about Noida).

_MONTH_WORDS = r"(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\.?"
_WEEKDAYS = r"(?:mon|tues?|wed(?:nes)?|thu(?:rs?)?|fri|sat(?:ur)?|sun)(?:day)?"
_DAY_SPAN_RE = re.compile(
    rf"(?:\b(?:on|for|of|ko|ka|ki|ke)\s+)?(?P<day>"
    rf"\b\d{{1,2}}(?:st|nd|rd|th)?\s+(?:of\s+)?{_MONTH_WORDS}(?:,?\s*\d{{4}})?"
    rf"|\b{_MONTH_WORDS}\s+\d{{1,2}}(?:st|nd|rd|th)?(?:,?\s*\d{{4}})?"
    rf"|\b\d{{4}}-\d{{2}}-\d{{2}}\b|\b\d{{1,2}}[/-]\d{{1,2}}[/-]\d{{2,4}}\b"
    rf"|\bday\s+after\s+tomorrow\b|\btomorrow\b|\btmrw\b|\byesterday\b|\btoday\b|\baaj\b"
    rf"|\b(?:this|next|coming|last)\s+{_WEEKDAYS}\b)"
    rf"(?:\s+(?:ko|ka|ki|ke)\b)?", re.IGNORECASE)
# Hindi function words in Latin letters - dropped before matching; "mausam"
# is the weather. "abhi"/"filhaal" mean "now": QA (Oct 15) "calgary ka mausam
# abhi kaisa hai" matched nothing and fell to the web-search model.
# (detect() above uses this too - it is only called after this module loads.
# An earlier, narrower definition above detect() was shadowed by this one.)
# "ko" never as the first word, so the place "Ko Samui" is left alone.
_HINGLISH_RE = re.compile(r"\b(?:(?<=\S )ko|ka|ki|ke|mein|me|kya|hai|hain|hoga|hogi|rahega|kaisa|kaisi|"
                          r"kaise|kesa|kitna|kitni|abhi|filhaal|batao|bataiye|bata|bataye|"
                          r"dikhao|please|pls|plz)\b", re.IGNORECASE)
_MAUSAM_RE = re.compile(r"\bmausam\b", re.IGNORECASE)


def _split_day(text: str):
    """(text without its date phrase, the date phrase or None)."""
    m = _DAY_SPAN_RE.search(text)
    if not m:
        return text, None
    rest = (text[:m.start()] + " " + text[m.end():])
    return re.sub(r"\s+", " ", rest).strip(), m.group("day")


def _resolve_day(day_text, today):
    """The date a phrase names, or None (then: today / current)."""
    if not day_text:
        return None
    lowered = day_text.strip().lower()
    if lowered in ("today", "aaj"):
        return today
    try:
        import services.date_query_resolver as dqr
        resolved = dqr.resolve(day_text, today)
    except Exception:
        return None
    if isinstance(resolved, dict) and resolved.get("type") == "single":
        return resolved.get("date")
    return None


def parse(query: str, context=None, today=None):
    """{"kind": "weather"|"time", "place": str|None, "day": date|None,
    "day_text": str|None} for a live question - including a date ("1 Nov
    2026 ko Calgary weather", "calgary weather tomorrow") and a follow-up to
    the previous live answer in `context` - else None."""
    from datetime import date as _date
    today = today or datetime.now(timezone.utc).date()
    text = _fold_day_typos((query or "").strip().replace("’", "'"))
    if not text or _HR_WORDS_RE.search(text):
        return None
    # The date phrase out first, so "weather in calgary yesterday" is about
    # "calgary", then the Hindi particles.
    rest, day_text = _split_day(text)
    rest = _MAUSAM_RE.sub("weather", rest)
    rest = re.sub(r"\s+", " ", _HINGLISH_RE.sub(" ", rest)).strip()
    hit = (detect(rest) if rest else None) or detect(text)
    if hit:
        kind, place = hit
        day = _resolve_day(day_text, today) if kind == "weather" else None
        if isinstance(day, _date) and day == today:
            day = None
        return {"kind": kind, "place": place, "day": day, "day_text": day_text}
    return _followup(text, context or [], today)


_ASKED_FOR_CITY = "Which city would you like the weather for"
_ASKED_FOR_CITY_TIME = "Which city would you like the time for"


def _ask_for_city(kind: str, unrecognised: str) -> str:
    """Asked when what looked like a place is not one. Live (Oct 15): "what
    is weather toaday" answered 'I couldn't find a place called "toaday"' - a
    dead end. Starts with the same words as the plain "Which city?" question,
    so the next reply ("noida") is read as the answer to it."""
    lead = _ASKED_FOR_CITY if kind == "weather" else _ASKED_FOR_CITY_TIME
    return (f"{lead}? I couldn't recognise \"{unrecognised}\" as a place - please tell me the "
            f"city and country (e.g. \"{kind} in Calgary, Canada\").")
# Every heading a live weather answer opens with. "Current weather in" was
# missing after that heading changed, so no follow-up was recognised (QA
# TP-030/031/052-056: "and in Edmonton?", "what about tomorrow?", "how old is
# this data?" were all answered as fresh questions - one claimed the data came
# from AccuWeather).
_LIVE_ANSWER_MARKERS = ("Current conditions in ", "Current weather in ",
                        "The latest weather data I could get for ",
                        "Forecast for ", "Recorded weather for ", "Weather forecasts only go",
                        "Hourly forecast for ", "Tonight in ", _ASKED_FOR_CITY)
_FOLLOWUP_PLACE_RE = re.compile(
    r"^\s*(?:(?:and|what|how)\s+(?:about|abt)\s+|and\s+|in\s+|for\s+|at\s+)?"
    r"(?P<place>[a-z][a-z .,'\-]{1,60}?)\s*\??\s*$", re.IGNORECASE)
# "thanks" after a weather answer is not a city to look up.
_ACKNOWLEDGEMENT_RE = re.compile(
    r"^\s*(?:ok(?:ay)?|k|thanks?|thank\s+you|thx|ty|cool|great|nice|got\s+it|fine|sure|yes|"
    r"no|nope|yeah|yep|alright|perfect|awesome|good|shukriya|dhanyavaad|theek\s+hai)"
    r"(?:\s+(?:so\s+much|a\s+lot|thanks?))?\s*[.!]*\s*$", re.IGNORECASE)


# A new topic, not a city - "bitcoin price right now" after a weather answer
# was read as a follow-up asking for the weather in "bitcoin price" (Oct 16).
_OTHER_TOPIC_RE = re.compile(
    r"\b(?:price|prices|rate|rates|cost|value|worth|score|scores|news|headlines?|stock|stocks|"
    r"shares?|market|markets|bitcoin|btc|crypto|ethereum|eth|gold|silver|petrol|diesel|"
    r"dollar|rupee|euro|exchange|currency|match|cricket|football|ipl|movie|movies|song|recipe|"
    r"joke|population|meaning|definition|leave|salary|policy|holiday|email|translate)\b",
    re.IGNORECASE)


def _followup(text, context, today):
    """A reply to the previous turn's live answer: a city after "Which city?",
    "what about Delhi?", "and tomorrow?". Only when that answer is the
    assistant's LAST message - nothing older is picked up."""
    last_assistant = next((m.get("content") or "" for m in reversed(context)
                           if m.get("role") == "assistant"), "")
    if not last_assistant or _ACKNOWLEDGEMENT_RE.match(text):
        return None
    which = re.match(rf'^{_WHICH_PLACE}"(?P<name>[^"]+)"', last_assistant)
    if which:
        return _which_place_reply(text, which.group("name"), last_assistant, context, today)
    is_weather = any(last_assistant.startswith(m) or m in last_assistant[:80]
                     for m in _LIVE_ANSWER_MARKERS)
    is_time = bool(re.match(r"^It's \d{1,2}:\d{2} [AP]M on ", last_assistant)
                   or last_assistant.startswith(_ASKED_FOR_CITY_TIME))
    if not (is_weather or is_time):
        return None
    kind = "time" if is_time else "weather"
    rest, day_text = _split_day(text)
    rest = re.sub(r"\s+", " ", _HINGLISH_RE.sub(" ", _MAUSAM_RE.sub("weather", rest))).strip(" ?.!")
    rest = re.sub(r"^(?:and|what|how)\s+(?:about|abt)\b|^and\b", "", rest, flags=re.IGNORECASE).strip()
    # The place the previous question was about, for "and tomorrow?".
    # Each earlier message read with ITS own history, so "what about delhi?"
    # counts - otherwise "and tomorrow?" after it went back to the first city.
    previous_place = None
    for i in range(len(context) - 1, -1, -1):
        if context[i].get("role") == "user":
            earlier = parse(context[i].get("content") or "", context[:i], today)
            if earlier and earlier.get("place"):
                previous_place = earlier["place"]
                break
    # Another topic ends the follow-up - "gold rate today" is not "the same
    # city, today".
    if _OTHER_TOPIC_RE.search(rest):
        return None
    m = _FOLLOWUP_PLACE_RE.match(rest) if rest else None
    words = rest.split()
    place = None
    if (m and len(words) <= 4 and not re.search(r"\b(?:weather|time|what|how|why|who)\b", rest, re.I)
            and not _OTHER_TOPIC_RE.search(rest)):
        place = _clean_place(m.group("place"))
    if place is None and not day_text:
        return None
    if place is None:
        if (last_assistant.startswith((_ASKED_FOR_CITY, _ASKED_FOR_CITY_TIME))
                or not previous_place):
            return None
        place = previous_place
    # The city answers "Which city?" - the day comes from the question it
    # answers ("weather tomorrow" -> "Which city?" -> "noida" is tomorrow).
    if (not day_text and kind == "weather"
            and last_assistant.startswith((_ASKED_FOR_CITY, _ASKED_FOR_CITY_TIME))):
        for i in range(len(context) - 1, -1, -1):
            if context[i].get("role") == "user":
                asked = parse(context[i].get("content") or "", context[:i], today)
                day_text = asked.get("day_text") if asked else None
                break
    day = _resolve_day(day_text, today) if kind == "weather" else None
    if day == today:
        day = None
    return {"kind": kind, "place": place, "day": day, "day_text": day_text}


def _which_place_reply(text, name, last_assistant, context, today):
    """The reply to "There's more than one "Springfield" ... Which one?":
    "missouri", "Springfield, Massachusetts", "the one in illinois". The
    question's own day ("... tomorrow") is kept."""
    reply = re.sub(r"^(?:i\s+meant?|the\s+one\s+in|one\s+in|in)\s+", "",
                   text.strip(" ?.!"), flags=re.IGNORECASE).strip(" ,")
    if (not reply or len(reply.split()) > 5
            or re.search(r"\b(?:weather|time|what|how|why|who)\b", reply, re.IGNORECASE)):
        return None
    place = reply if name.lower() in reply.lower() else f"{name}, {reply}"
    kind = "time" if 'e.g. "time in' in last_assistant else "weather"
    day = day_text = None
    for i in range(len(context) - 1, -1, -1):
        if context[i].get("role") == "user":
            earlier = parse(context[i].get("content") or "", context[:i], today)
            if earlier:
                day, day_text = earlier.get("day"), earlier.get("day_text")
            break
    return {"kind": kind, "place": place, "day": day if kind == "weather" else None,
            "day_text": day_text}


def _clean_place(raw):
    place = re.sub(r"\s+", " ", (raw or "").strip(" .,'-")).strip()
    place = re.sub(r"^(?:the\s+city\s+of\s+|city\s+of\s+)", "", place, flags=re.IGNORECASE)
    while True:
        stripped = _PLACE_FILLER_RE.sub("", place).strip(" .,'-")
        if stripped == place:
            break
        place = stripped
    if not place or place.lower() in _NOT_A_PLACE or len(place) < 2:
        return None
    # A question or a command is never a place name: "what is" (from "what is
    # temperature today"), "how is", "tell me".
    if re.match(r"^(?:what|whats|what's|how|hows|how's|is|are|was|tell|show|give|get|check|"
                r"can|could|will|would|do|does)\b", place, re.IGNORECASE):
        return None
    return place


# -- Looking it up ---------------------------------------------------------------

def _has_words(where: str, words) -> bool:
    """Every word appears in `where` as a WHOLE word - "and in edmonton" is not
    Edmonton, England just because "england" contains "and" and "in" (QA TP-030)."""
    return all(re.search(rf"\b{re.escape(w)}\b", where) for w in words if w)


async def _geocode(place: str):
    """The best match for `place` ("calgary", "calgary, canada", "paris france"),
    or None. A trailing country/region narrows the match."""
    name, _, hint = place.partition(",")
    words = name.split()
    candidates = [(name.strip(), hint.strip())]
    if not hint:
        # Every split into "name" + "region/country": "paris france",
        # "calgary alberta canada", "san francisco california usa". Longest name first.
        for i in range(len(words) - 1, 0, -1):
            candidates.append((" ".join(words[:i]), " ".join(words[i:])))
    async with httpx.AsyncClient(timeout=_TIMEOUT) as client:
        for search, region in candidates:
            resp = await client.get(_GEOCODE_URL, params={"name": search, "count": 10,
                                                          "language": "en", "format": "json"})
            resp.raise_for_status()
            results = resp.json().get("results") or []
            if region:
                region_l = region.lower()
                for short, full in _COUNTRY_ALIASES.items():
                    region_l = re.sub(rf"\b{short}\b", full, region_l)
                region_words = region_l.split()
                narrowed = [r for r in results
                            if _has_words(" ".join(str(r.get(k) or "") for k in
                                                   ("country", "country_code", "admin1")).lower(),
                                          region_words)]
                if narrowed:
                    results = narrowed
                elif search != name.strip():
                    continue
            if results:
                # The most populous match: "london" is London, England. Among
                # exact-name matches when there are any - "vancouver" was
                # Vancouver Island (870k) over the city (600k).
                exact = [r for r in results
                         if (r.get("name") or "").lower() == search.strip().lower()]
                best = max(exact or results, key=lambda r: r.get("population") or 0)
                if not region:
                    rivals = _same_name_rivals(results, search)
                    if len(rivals) > 1:
                        best = {**best, "alternatives": rivals}
                return best
    return None


#: A second place with the same name at least this fraction of the largest
#: one's population makes the name ambiguous: Springfield, Missouri (170k) vs
#: Massachusetts (154k) is; London, England vs London, Ontario is not.
AMBIGUOUS_POPULATION_RATIO = float(os.getenv("LIVE_AMBIGUOUS_PLACE_RATIO", "0.5"))


def _same_name_rivals(results, name):
    """The places called exactly `name` that are each big enough for "the
    most populous one" to be a guess, largest first - or [] when one clearly
    dominates. QA (Oct 15): "current weather in springfield" was silently
    answered for Springfield, Missouri."""
    same = [r for r in results if (r.get("name") or "").lower() == name.strip().lower()]
    seen, distinct = set(), []
    for r in sorted(same, key=lambda r: r.get("population") or 0, reverse=True):
        key = (r.get("admin1"), r.get("country"))
        if key not in seen:
            seen.add(key)
            distinct.append(r)
    top = (distinct[0].get("population") or 0) if distinct else 0
    if top <= 0:
        return []
    # A big city is a real rival even when another one is bigger still -
    # Victoria, Hong Kong (957k) vs Victoria, BC (290k); Hyderabad, India vs
    # Pakistan - unless the biggest is a national capital (London, Paris).
    capital = str(distinct[0].get("feature_code") or "") == "PPLC"
    rivals = [r for r in distinct
              if (r.get("population") or 0) >= AMBIGUOUS_POPULATION_RATIO * top
              or (not capital and (r.get("population") or 0) >= BIG_CITY_RIVAL_POPULATION)]
    return rivals if len(rivals) > 1 else []


#: A same-name city at least this big makes a name ambiguous (see above).
BIG_CITY_RIVAL_POPULATION = int(os.getenv("LIVE_BIG_CITY_RIVAL_POPULATION", "250000"))


_WHICH_PLACE = "There's more than one "


def _which_place_answer(kind: str, place: str, alternatives) -> str:
    options = [_place_label(r) for r in alternatives[:4]]
    listed = "; ".join(options[:-1]) + f"; or {options[-1]}"
    first = alternatives[0]
    # A territory with no country recorded (Hong Kong) is named by its code,
    # not its district: "Victoria, Hong Kong", not "Victoria, Central and Western".
    region = (_COUNTRY_CODE_NAMES.get(str(first.get("country_code") or "").upper())
              if not first.get("country") else None) or first.get("admin1") or first.get("country") or ""
    example = f"{kind} in {alternatives[0].get('name')}, {region}"
    return (f"{_WHICH_PLACE}\"{alternatives[0].get('name')}\" - {listed}. "
            f"Which one did you mean? (e.g. \"{example}\")")


_ARCHIVE_URL = os.getenv("LIVE_WEATHER_ARCHIVE_URL", "https://archive-api.open-meteo.com/v1/archive")
#: How far ahead a daily forecast is offered (Open-Meteo's own limit is 16
#: days including today); further than this is said to be out of reach.
FORECAST_DAYS_AHEAD = 15
#: How far back the forecast API still serves a past day; older days come
#: from the archive.
RECENT_PAST_DAYS = 90


async def _fetch_weather(params: dict, url: str = None) -> dict:
    async with httpx.AsyncClient(timeout=_TIMEOUT) as client:
        resp = await client.get(url or _WEATHER_URL, params=params)
        resp.raise_for_status()
        return resp.json()


# The geocoder leaves `country` empty for some territories - "Victoria,
# Central and Western" was Hong Kong with no country shown (QA TP-026).
_COUNTRY_CODE_NAMES = {"HK": "Hong Kong", "MO": "Macao", "TW": "Taiwan", "PS": "Palestine",
                       "PR": "Puerto Rico", "XK": "Kosovo"}


def _place_label(geo: dict) -> str:
    country = geo.get("country") or _COUNTRY_CODE_NAMES.get(str(geo.get("country_code") or "").upper())
    parts = [geo.get("name"), geo.get("admin1"), country]
    out = []
    for p in parts:
        if p and p not in out:
            out.append(p)
    return ", ".join(out)


# Zones the tz database names only by offset ("+08"): QA TP-009/010 showed
# "2:00 PM +08" for Singapore and "+04" for Dubai.
_TZ_ABBREVIATIONS = {
    "Asia/Singapore": "SGT", "Asia/Dubai": "GST", "Asia/Muscat": "GST", "Asia/Kuala_Lumpur": "MYT",
    "Asia/Manila": "PHT", "Asia/Bangkok": "ICT", "Asia/Ho_Chi_Minh": "ICT", "Asia/Jakarta": "WIB",
    "Asia/Riyadh": "AST", "Asia/Qatar": "AST", "Asia/Bahrain": "AST", "Asia/Kuwait": "AST",
    "Asia/Kathmandu": "NPT", "Asia/Tehran": "IRST", "Asia/Kabul": "AFT", "Asia/Colombo": "IST",
    "Asia/Yerevan": "AMT", "Asia/Tbilisi": "GET", "Asia/Baku": "AZT", "Asia/Tashkent": "UZT",
    "Asia/Almaty": "ALMT", "America/Sao_Paulo": "BRT", "America/Argentina/Buenos_Aires": "ART",
    "America/Bogota": "COT", "America/Lima": "PET", "America/Santiago": "CLT",
    "America/Caracas": "VET", "Europe/Istanbul": "TRT", "Europe/Moscow": "MSK",
}


def _abbr(dt: datetime) -> str:
    """The zone's short name ("MDT", "SGT"), never a bare offset like "+08"."""
    name = dt.tzname() or ""
    if name.startswith(("+", "-")) or not name:
        return _TZ_ABBREVIATIONS.get(getattr(dt.tzinfo, "key", ""), name)
    return name


def _tz_label(now_local: datetime) -> str:
    abbr = _abbr(now_local)
    offset = now_local.utcoffset() or timedelta(0)
    total = int(offset.total_seconds() // 60)
    sign = "+" if total >= 0 else "−"
    h, m = divmod(abs(total), 60)
    utc = f"UTC{sign}{h}" + (f":{m:02d}" if m else "")
    if total == 0:
        utc = "UTC"
    return f"{abbr}, {utc}" if abbr and abbr != utc and not abbr.startswith(("+", "-")) else utc


def _fmt_time(dt: datetime) -> str:
    return dt.strftime("%I:%M %p").lstrip("0")


def _fmt_day(dt: datetime) -> str:
    return dt.strftime("%A, %d %B %Y").replace(" 0", " ")


_WEATHER_CODES = {
    0: "Clear sky", 1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast",
    45: "Fog", 48: "Freezing fog", 51: "Light drizzle", 53: "Drizzle", 55: "Heavy drizzle",
    56: "Light freezing drizzle", 57: "Freezing drizzle", 61: "Light rain", 63: "Rain",
    65: "Heavy rain", 66: "Light freezing rain", 67: "Freezing rain", 71: "Light snow",
    73: "Snow", 75: "Heavy snow", 77: "Snow grains", 80: "Light rain showers",
    81: "Rain showers", 82: "Heavy rain showers", 85: "Light snow showers",
    86: "Heavy snow showers", 95: "Thunderstorm", 96: "Thunderstorm with hail",
    99: "Thunderstorm with heavy hail",
}


async def weather_answer(place: str, now_utc: datetime | None = None, day=None) -> dict:
    """{"answer": text, "source": ..., "observed_at": ISO or None,
    "stale": bool, "available": bool}. With `day` (a date other than the
    place's today): that day's forecast, or its recorded weather if past."""
    now_utc = now_utc or datetime.now(timezone.utc)
    if not place:
        # Live, a bare "weather" was answered for India - the model's guess
        # at where the user is.
        return {"answer": "Which city would you like the weather for? (e.g. \"weather in Calgary\")",
                "source": None, "observed_at": None, "stale": False, "available": False}
    unavailable = {
        "answer": (f"I can't get live weather for {place} right now, so I won't guess - an "
                   f"old reading presented as current would be wrong. Please check your local "
                   f"weather service (for Canada, weather.gc.ca) for the latest conditions."),
        "source": SOURCE_NAME, "observed_at": None, "stale": False, "available": False,
    }
    try:
        geo = await _geocode(place)
        if not geo:
            return {**unavailable, "source": None, "answer": _ask_for_city("weather", place)}
        if geo.get("alternatives"):
            return {**unavailable, "source": None,
                    "answer": _which_place_answer("weather", place, geo["alternatives"])}
        if day is not None:
            local_today = now_utc.astimezone(ZoneInfo(geo.get("timezone") or "UTC")).date()
            if day != local_today:
                return await _day_weather(geo, day, local_today, unavailable)
        params = {
            "latitude": geo["latitude"], "longitude": geo["longitude"],
            "timezone": geo.get("timezone") or "auto",
            "current": "temperature_2m,apparent_temperature,relative_humidity_2m,"
                       "weather_code,wind_speed_10m,pressure_msl,precipitation",
            "daily": "temperature_2m_max,temperature_2m_min,precipitation_probability_max",
            "forecast_days": 1,
        }
        data = await _fetch_weather(params)
    except Exception as exc:
        logger.warning("[LiveInfo] weather lookup failed for %r: %s", place, exc)
        return unavailable

    current = data.get("current") or {}
    tz = ZoneInfo(data.get("timezone") or geo.get("timezone") or "UTC")
    try:
        valid_at = datetime.fromisoformat(current["time"]).replace(tzinfo=tz)
    except Exception:
        logger.warning("[LiveInfo] weather response had no usable time: %s", current)
        return unavailable
    now_local = now_utc.astimezone(tz)
    age = now_utc - valid_at.astimezone(timezone.utc)
    stale = age > STALE_AFTER

    label = _place_label(geo)
    when = f"{_fmt_time(valid_at)} {_abbr(valid_at)} on {_fmt_day(valid_at)}"
    lines = []
    if stale:
        lines.append(f"**The latest weather data I could get for {label} is from {when}** - "
                     f"about {int(age.total_seconds() // 3600)} hour(s) old, so it may not "
                     f"reflect conditions right now.")
    else:
        lines.append(f"**Current weather in {label}** (as of {when}, local time; it is "
                     f"{_fmt_time(now_local)} there now):")
    sky = _WEATHER_CODES.get(current.get("weather_code"), None)
    if current.get("temperature_2m") is not None:
        feels = current.get("apparent_temperature")
        lines.append(f"- Temperature: {current['temperature_2m']:.1f} °C"
                     + (f" (feels like {feels:.1f} °C)" if feels is not None else ""))
    if sky:
        lines.append(f"- Sky: {sky}")
    if current.get("relative_humidity_2m") is not None:
        lines.append(f"- Humidity: {current['relative_humidity_2m']:.0f}%")
    if current.get("wind_speed_10m") is not None:
        lines.append(f"- Wind: {current['wind_speed_10m']:.0f} km/h")
    if current.get("pressure_msl") is not None:
        lines.append(f"- Pressure: {current['pressure_msl'] / 10:.1f} kPa")
    daily = data.get("daily") or {}
    hi, lo = (daily.get("temperature_2m_max") or [None])[0], (daily.get("temperature_2m_min") or [None])[0]
    if hi is not None and lo is not None:
        pop = (daily.get("precipitation_probability_max") or [None])[0]
        lines.append(f"\n*Forecast for today*: high {hi:.0f} °C, low {lo:.0f} °C"
                     + (f", {pop:.0f}% chance of precipitation" if pop is not None else "") + ".")
    return {"answer": "\n".join(lines), "source": SOURCE_NAME,
            "observed_at": valid_at.isoformat(), "stale": stale, "available": True}


async def _day_weather(geo: dict, day, local_today, unavailable: dict) -> dict:
    """One day's weather away from today: a forecast (labelled as one) up to
    FORECAST_DAYS_AHEAD days out, the recorded weather for a past day, and a
    plain "too far ahead" - never a guess - beyond the forecast range."""
    label = _place_label(geo)
    when = _fmt_day(datetime(day.year, day.month, day.day))
    ahead = (day - local_today).days
    base = {"source": SOURCE_NAME, "observed_at": None, "stale": False}
    if ahead > FORECAST_DAYS_AHEAD:
        return {**base, "available": False, "answer": (
            f"Weather forecasts only go up to {FORECAST_DAYS_AHEAD} days ahead, so I can't "
            f"give a reliable forecast for {label} on {when} yet - it's {ahead} days away. "
            f"Ask me again closer to the date and I'll give you the forecast then.")}
    daily_vars = ("weather_code,temperature_2m_max,temperature_2m_min,precipitation_sum,"
                  "wind_speed_10m_max")
    if ahead > 0:
        daily_vars += ",precipitation_probability_max"
    params = {"latitude": geo["latitude"], "longitude": geo["longitude"],
              "timezone": geo.get("timezone") or "auto", "daily": daily_vars,
              "start_date": day.isoformat(), "end_date": day.isoformat()}
    url = _ARCHIVE_URL if ahead < -RECENT_PAST_DAYS else None
    try:
        data = await _fetch_weather(params, url)
        daily = data.get("daily") or {}
        first = lambda key: (daily.get(key) or [None])[0]
        hi, lo = first("temperature_2m_max"), first("temperature_2m_min")
        if hi is None or lo is None:
            raise ValueError(f"no daily values: {daily}")
    except Exception as exc:
        logger.warning("[LiveInfo] daily weather lookup failed for %r on %s: %s",
                       geo.get("name"), day, exc)
        return {**unavailable, "answer": (f"I can't get the weather for {label} on {when} right "
                                          f"now, so I won't guess.")}
    if ahead > 0:
        lines = [f"**Forecast for {label} on {when}** ({ahead} day{'s' if ahead != 1 else ''} "
                 f"ahead - forecasts can still change):"]
    else:
        lines = [f"**Recorded weather for {label} on {when}:**"]
    sky = _WEATHER_CODES.get(first("weather_code"))
    lines.append(f"- High {hi:.0f} °C, low {lo:.0f} °C")
    if sky:
        lines.append(f"- Sky: {sky}")
    pop = first("precipitation_probability_max")
    rain = first("precipitation_sum")
    if pop is not None:
        lines.append(f"- Chance of precipitation: {pop:.0f}%")
    elif rain is not None:
        lines.append(f"- Precipitation: {rain:.1f} mm")
    wind = first("wind_speed_10m_max")
    if wind is not None:
        lines.append(f"- Wind up to {wind:.0f} km/h")
    return {**base, "available": True, "answer": "\n".join(lines),
            "observed_at": None, "day": day.isoformat(),
            "forecast": ahead > 0}


async def time_answer(place: str | None, now_utc: datetime | None = None) -> dict:
    """{"answer": text, "timezone": IANA name or None, "available": bool}.
    Computed from the server clock and the place's IANA timezone - never by
    the model."""
    now_utc = now_utc or datetime.now(timezone.utc)
    if not place:
        tz_name = os.getenv("QUOTA_TIMEZONE", "UTC")
        try:
            tz = ZoneInfo(tz_name)
        except Exception:
            tz_name, tz = "UTC", ZoneInfo("UTC")
        local = now_utc.astimezone(tz)
        return {"answer": (f"It's {_fmt_time(local)} on {_fmt_day(local)} in {tz_name} "
                           f"({_tz_label(local)}) - the app's time zone. I don't know where you "
                           f"are, so tell me a city (e.g. \"time in Calgary\") for its local time."),
                "timezone": tz_name, "available": True}
    try:
        geo = await _geocode(place)
    except Exception as exc:
        logger.warning("[LiveInfo] geocoding failed for %r: %s", place, exc)
        return {"answer": (f"I can't look up the time zone for \"{place}\" right now, so I won't "
                           f"guess - please try again in a moment."),
                "timezone": None, "available": False}
    if not geo or not geo.get("timezone"):
        return {"answer": _ask_for_city("time", place), "timezone": None, "available": False}
    # Only ask when the answer would differ: every Springfield in Missouri
    # and Illinois has the same clock.
    if len({r.get("timezone") for r in geo.get("alternatives") or []}) > 1:
        return {"answer": _which_place_answer("time", place, geo["alternatives"]),
                "timezone": None, "available": False}
    local = now_utc.astimezone(ZoneInfo(geo["timezone"]))
    return {"answer": (f"It's {_fmt_time(local)} on {_fmt_day(local)} in {_place_label(geo)} "
                       f"({_tz_label(local)})."),
            "timezone": geo["timezone"], "available": True}


#: How big a place must be before a bare word that names it is read as the
#: place rather than an unknown employee - see is_known_place.
KNOWN_PLACE_MIN_POPULATION = int(os.getenv("KNOWN_PLACE_MIN_POPULATION", "100000"))


async def is_known_place(text: str) -> bool:
    """True when `text` is, exactly, the name of a city of at least
    KNOWN_PLACE_MIN_POPULATION people ("Calgary", "New Delhi"). Used only
    after a guessed employee name matched nobody - so a real employee called
    Victoria or Austin is still found first. False on any lookup failure."""
    name = (text or "").strip(" .!?")
    if not name or len(name) > 60:
        return False
    # "Calgary Alberta Canada" / "Calgary, Canada": a city followed by its
    # region and/or country. Live (Oct 15): the whole string was looked up as
    # one name, matched nothing, and a manager got the employee picker.
    words = [w for w in re.split(r"[,\s]+", name) if w]
    splits = [(" ".join(words[:k]), words[k:]) for k in range(len(words), 0, -1)
              if len(words) - k <= 3]
    try:
        async with httpx.AsyncClient(timeout=min(_TIMEOUT, 3.0)) as client:
            for city, region in splits:
                resp = await client.get(_GEOCODE_URL, params={"name": city, "count": 10,
                                                              "language": "en", "format": "json"})
                resp.raise_for_status()
                for r in resp.json().get("results") or []:
                    if (r.get("name") or "").lower() != city.lower():
                        continue
                    if not region:
                        if (r.get("population") or 0) >= KNOWN_PLACE_MIN_POPULATION:
                            return True
                        continue
                    where = " ".join(str(r.get(k) or "") for k in
                                     ("admin1", "admin2", "country", "country_code")).lower()
                    region_words = [_COUNTRY_ALIASES.get(w.lower(), w.lower()) for w in region]
                    # Named with its region/country, a town of any real size is a place.
                    if (_has_words(where, region_words)
                            and (r.get("population") or 0) >= 1000):
                        return True
    except Exception as exc:
        logger.info("[LiveInfo] place check failed for %r: %s", name, exc)
        return False
    return False


# -- A place on its own: live snapshot + overview ---------------------------------
#
# "canada calgary alberta" got a web-search paragraph only. A bare place name
# now leads with what only a live source gets right - the local time, the
# weather now, today's high/low - and the model's overview follows it.

_BARE_PLACE_RE = re.compile(r"^\s*[a-z][a-z .,'\-]{1,80}\s*[.!?]*\s*$", re.IGNORECASE)
_NOT_BARE_PLACE_RE = re.compile(
    r"\b(?:what|who|why|how|when|where|which|is|are|was|tell|show|give|explain|define|"
    r"vs|versus|history|meaning|population|capital|weather|time|temperature)\b", re.IGNORECASE)


def looks_like_bare_place(text: str) -> bool:
    """A message that is only a place name ("Calgary Alberta Canada",
    "canada calgary alberta", "Delhi") - 1 to 6 words, no question."""
    words = [w for w in re.split(r"[,\s]+", text or "") if w]
    return (1 <= len(words) <= 6 and bool(_BARE_PLACE_RE.match(text or ""))
            and not _NOT_BARE_PLACE_RE.search(text or ""))


def _is_country(r: dict) -> bool:
    return str(r.get("feature_code") or "").startswith("PCL")


async def resolve_place(text: str):
    """The place a short message names, its words in any order - "Calgary
    Alberta Canada", "canada calgary alberta", "Calgary, Canada", "Delhi",
    "Canada" - or None. A city alone must be a well-known one
    (KNOWN_PLACE_MIN_POPULATION); with its region or country named, any real
    town is. False positives are what this guards against: it decides whether
    a word is answered as a place."""
    words = [w for w in re.split(r"[,\s]+", (text or "").strip(" .!?")) if w]
    if not 1 <= len(words) <= 6:
        return None
    windows = [(i, j) for size in range(min(3, len(words)), 0, -1)
               for i in range(len(words) - size + 1) for j in [i + size]]
    seen = {}
    try:
        async with httpx.AsyncClient(timeout=min(_TIMEOUT, 3.0)) as client:
            for i, j in windows:
                city = " ".join(words[i:j])
                rest = [_COUNTRY_ALIASES.get(w.lower(), w.lower()) for w in words[:i] + words[j:]]
                if city.lower() not in seen:
                    resp = await client.get(_GEOCODE_URL, params={"name": city, "count": 10,
                                                                  "language": "en", "format": "json"})
                    resp.raise_for_status()
                    seen[city.lower()] = resp.json().get("results") or []
                for r in seen[city.lower()]:
                    if (r.get("name") or "").lower() != city.lower():
                        continue
                    if _is_country(r):
                        if not rest:
                            return r
                        continue
                    if rest:
                        where = " ".join(str(r.get(k) or "") for k in
                                         ("admin1", "admin2", "country", "country_code")).lower()
                        if _has_words(where, rest) and (r.get("population") or 0) >= 1000:
                            return r
                    elif (r.get("population") or 0) >= KNOWN_PLACE_MIN_POPULATION:
                        return r
    except Exception as exc:
        logger.info("[LiveInfo] place lookup failed for %r: %s", text, exc)
    return None


async def place_snapshot(geo: dict, now_utc: datetime | None = None) -> str:
    """The live facts about a place, from the live sources only: local time,
    the weather now and today's high/low (a city), population. Every figure
    is fetched, none is the model's."""
    now_utc = now_utc or datetime.now(timezone.utc)
    label = _place_label(geo)
    lines = [f"**{label} - right now**"]
    tz_name = geo.get("timezone")
    if tz_name:
        local = now_utc.astimezone(ZoneInfo(tz_name))
        lines.append(f"- Local time: {_fmt_time(local)}, {_fmt_day(local)} ({_tz_label(local)})")
    elif _is_country(geo):
        lines.append("- Local time: spans several time zones - ask for a city "
                     "(e.g. \"time in Toronto\") for its local time")
    if not _is_country(geo):
        try:
            data = await _fetch_weather({
                "latitude": geo["latitude"], "longitude": geo["longitude"],
                "timezone": tz_name or "auto",
                "current": "temperature_2m,apparent_temperature,weather_code,relative_humidity_2m",
                "daily": "temperature_2m_max,temperature_2m_min", "forecast_days": 1})
            current = data.get("current") or {}
            tz = ZoneInfo(data.get("timezone") or tz_name or "UTC")
            valid_at = datetime.fromisoformat(current["time"]).replace(tzinfo=tz)
            if now_utc - valid_at.astimezone(timezone.utc) <= STALE_AFTER:
                sky = _WEATHER_CODES.get(current.get("weather_code"))
                lines.append(f"- Weather: {current['temperature_2m']:.1f} °C"
                             + (f", {sky.lower()}" if sky else "")
                             + (f" (feels like {current['apparent_temperature']:.1f} °C)"
                                if current.get("apparent_temperature") is not None else "")
                             + f" - as of {_fmt_time(valid_at)}")
                daily = data.get("daily") or {}
                hi = (daily.get("temperature_2m_max") or [None])[0]
                lo = (daily.get("temperature_2m_min") or [None])[0]
                if hi is not None and lo is not None:
                    lines.append(f"- Today's forecast: high {hi:.0f} °C, low {lo:.0f} °C")
            else:
                lines.append("- Weather: the latest reading I could get is out of date, so "
                             "I've left it out")
        except Exception as exc:
            logger.info("[LiveInfo] snapshot weather failed for %r: %s", label, exc)
            lines.append("- Weather: live weather isn't available right now")
    if geo.get("population"):
        lines.append(f"- Population: about {geo['population']:,}")
    if geo.get("elevation") is not None and not _is_country(geo):
        lines.append(f"- Elevation: {geo['elevation']:.0f} m")
    return "\n".join(lines)


async def answer(kind: str, place: str | None, day=None) -> dict:
    if kind == "weather":
        return await weather_answer(place, day=day)
    return await time_answer(place)
