"""P1 (Oct 14): "current weather in calgary" at 12:18 PM MDT on 14 Oct was
answered "as of 5 PM MDT on 13 Oct" - a 19-hour-old observation copied from a
search-index snapshot and presented as current. "what time is it in X" was the
model converting from the app's IST clock in its head. And bare words like
"Calgary" or "current temperature in Delhi" reached the employee search.

The weather now and the time in a place are answered from a live source with
the reading's own timestamp (services/live_info); anything else live comes
from search results the model must date, or say it cannot.
"""
from datetime import datetime, timezone
from unittest.mock import AsyncMock

import pytest

import services.ai_service as ai_service
import services.classify_node as classify_node
import services.leave_slot_service as leave_slot_service
import services.live_info as live_info

CALGARY = {"name": "Calgary", "admin1": "Alberta", "country": "Canada",
           "latitude": 51.05, "longitude": -114.08, "timezone": "America/Edmonton",
           "population": 1306784}
# 12:18 PM MDT on 14 Oct 2026 - when the bug was reported.
ASKED_AT = datetime(2026, 10, 14, 18, 18, tzinfo=timezone.utc)


def _weather(time_local, temp=11.5):
    return {"timezone": "America/Edmonton",
            "current": {"time": time_local, "temperature_2m": temp, "apparent_temperature": 10.0,
                        "relative_humidity_2m": 40, "weather_code": 1, "wind_speed_10m": 12,
                        "pressure_msl": 1020.0},
            "daily": {"temperature_2m_max": [15.0], "temperature_2m_min": [3.0],
                      "precipitation_probability_max": [10]}}


@pytest.fixture
def calgary(monkeypatch):
    monkeypatch.setattr(live_info, "_geocode", AsyncMock(return_value=CALGARY))


# -- recognising the question --------------------------------------------------

@pytest.mark.parametrize("query,expected", [
    ("current weather in calgary", ("weather", "calgary")),
    ("calgary weather", ("weather", "calgary")),
    ("what is the temperature in Delhi now", ("weather", "Delhi")),
    ("current temperature in Delhi", ("weather", "Delhi")),
    ("how cold is it in toronto", ("weather", "toronto")),
    ("is it raining in mumbai", ("weather", "mumbai")),
    ("weather in paris, france", ("weather", "paris, france")),
    ("weather", ("weather", None)),
    ("what's the weather like today", ("weather", None)),
    ("what time is it in calgary", ("time", "calgary")),
    ("current time in delhi", ("time", "delhi")),
    ("time in london now", ("time", "london")),
    ("calgary time", ("time", "calgary")),
    ("what time is it", ("time", None)),
    ("current time", ("time", None)),
])
def test_live_questions(query, expected):
    assert live_info.detect(query) == expected


@pytest.mark.parametrize("query,expected", [
    ("weather calgary", ("weather", "calgary")),
    ("temperature calgary now", ("weather", "calgary")),
    ("calgary current weather", ("weather", "calgary")),
    ("calgary live weather", ("weather", "calgary")),
    ("Calgary ka weather batao", ("weather", "Calgary")),
    ("calgary weather kya hai", ("weather", "calgary")),
    ("current weather in calgary alberta canada", ("weather", "calgary alberta canada")),
    ("weather in calgary right now please", ("weather", "calgary")),
    ("Ko Samui weather", ("weather", "Ko Samui")),
])
def test_more_ways_of_asking_the_weather(query, expected):
    assert live_info.detect(query) == expected


@pytest.mark.parametrize("query", [
    "weather in calgary tomorrow", "will it rain in calgary tomorrow",
    "weather forecast for calgary this week", "1 Nov 2026 ko Calgary weather",
    "calgary weather on 5 november", "calgary weather next week",
    "weather in calgary on friday", "10 day forecast for calgary",
])
def test_a_question_about_another_day_is_not_answered_from_the_live_reading(query):
    # The live source has only NOW; answering these with current conditions
    # would present today's weather as the day asked about.
    assert live_info.detect(query) is None


@pytest.mark.parametrize("query", [
    "weather is nice today", "weather report", "weather was great", "weather conditions",
    "weather like", "weather update",
])
def test_weather_as_an_ordinary_word_is_not_a_place_lookup(query):
    result = live_info.detect(query)
    assert result is None or result[1] is None


@pytest.mark.parametrize("place", [
    "calgary alberta canada", "calgary, alberta", "calgary, canada", "calgary canada",
])
async def test_a_place_with_a_region_or_country_is_geocoded(place, monkeypatch):
    calls = []

    class Resp:
        def __init__(self, results): self._r = results
        def raise_for_status(self): pass
        def json(self): return {"results": self._r}

    class Client:
        def __init__(self, *a, **k): pass
        async def __aenter__(self): return self
        async def __aexit__(self, *a): return False
        async def get(self, url, params=None):
            calls.append(params["name"])
            # Open-Meteo matches a bare name, not a name with a region in it.
            return Resp([CALGARY] if params["name"].lower() == "calgary" else [])

    monkeypatch.setattr(live_info.httpx, "AsyncClient", Client)
    geo = await live_info._geocode(place)
    assert geo and geo["name"] == "Calgary" and geo["admin1"] == "Alberta"


async def test_a_country_abbreviation_and_a_multi_word_city_are_geocoded(monkeypatch):
    sf = {"name": "San Francisco", "admin1": "California", "country": "United States",
          "country_code": "US", "latitude": 37.77, "longitude": -122.42,
          "timezone": "America/Los_Angeles", "population": 873965}

    class Resp:
        def raise_for_status(self): pass
        def json(self): return {"results": [sf]}

    class Client:
        def __init__(self, *a, **k): pass
        async def __aenter__(self): return self
        async def __aexit__(self, *a): return False
        async def get(self, url, params=None):
            return Resp() if params["name"].lower() == "san francisco" else type(
                "Empty", (), {"raise_for_status": lambda s: None, "json": lambda s: {}})()

    monkeypatch.setattr(live_info.httpx, "AsyncClient", Client)
    for place in ("san francisco california usa", "san francisco usa", "san francisco california"):
        geo = await live_info._geocode(place)
        assert geo and geo["name"] == "San Francisco", place


@pytest.mark.parametrize("query", [
    "what time is my shift", "punch in time for today", "show my attendance for today",
    "weather was bad so i was late", "time off policy", "late arrival reason weather",
    "apply leave for tomorrow", "what is my check in time",
])
def test_hr_questions_are_not_live_info(query):
    assert live_info.detect(query) is None


# -- the weather ---------------------------------------------------------------

async def test_a_fresh_reading_is_current_with_its_own_timestamp(calgary, monkeypatch):
    monkeypatch.setattr(live_info, "_fetch_weather", AsyncMock(return_value=_weather("2026-10-14T12:15")))
    result = await live_info.weather_answer("calgary", now_utc=ASKED_AT)
    assert result["available"] and not result["stale"]
    assert "Current weather in Calgary, Alberta, Canada" in result["answer"]
    assert "as of 12:15 PM MDT on Wednesday, 14 October 2026" in result["answer"]
    assert "it is 12:18 PM there now" in result["answer"]
    assert "Forecast for today" in result["answer"]          # labelled as forecast


async def test_the_reported_19_hour_old_reading_is_never_called_current(calgary, monkeypatch):
    """The exact P1: 5 PM MDT on 13 Oct, asked at 12:18 PM MDT on 14 Oct."""
    monkeypatch.setattr(live_info, "_fetch_weather", AsyncMock(return_value=_weather("2026-10-13T17:00")))
    result = await live_info.weather_answer("calgary", now_utc=ASKED_AT)
    assert result["stale"] is True
    assert "Current weather" not in result["answer"]
    assert "latest weather data I could get" in result["answer"]
    assert "5:00 PM MDT on Tuesday, 13 October 2026" in result["answer"]
    assert "may not reflect conditions right now" in result["answer"]


async def test_no_live_source_means_no_guess(calgary, monkeypatch):
    monkeypatch.setattr(live_info, "_fetch_weather", AsyncMock(side_effect=OSError("down")))
    result = await live_info.weather_answer("calgary", now_utc=ASKED_AT)
    assert result["available"] is False
    assert "can't get live weather" in result["answer"] and "won't guess" in result["answer"]


async def test_an_unknown_place_asks_again(monkeypatch):
    """Asked for the city and country - not a dead-end "couldn't find" (Oct 15)."""
    monkeypatch.setattr(live_info, "_geocode", AsyncMock(return_value=None))
    result = await live_info.weather_answer("xyzqwv", now_utc=ASKED_AT)
    assert result["answer"].startswith("Which city would you like the weather for?")
    assert "\"xyzqwv\"" in result["answer"]


async def test_no_city_is_asked_for():
    result = await live_info.weather_answer(None)
    assert result["answer"].startswith("Which city")


# -- the time --------------------------------------------------------------------

async def test_the_time_in_a_place_comes_from_its_time_zone(calgary):
    result = await live_info.time_answer("calgary", now_utc=ASKED_AT)
    assert result["answer"] == ("It's 12:18 PM on Wednesday, 14 October 2026 in Calgary, "
                                "Alberta, Canada (MDT, UTC−6).")


async def test_winter_time_is_handled(calgary):
    jan = datetime(2026, 1, 14, 19, 18, tzinfo=timezone.utc)
    assert "(MST, UTC−7)" in (await live_info.time_answer("calgary", now_utc=jan))["answer"]


async def test_with_no_place_the_time_zone_is_named(monkeypatch):
    monkeypatch.setenv("QUOTA_TIMEZONE", "Asia/Kolkata")
    answer = (await live_info.time_answer(None, now_utc=ASKED_AT))["answer"]
    assert "11:48 PM on Wednesday, 14 October 2026 in Asia/Kolkata (IST, UTC+5:30)" in answer
    assert "I don't know where you are" in answer


# -- routing and the node ----------------------------------------------------------

@pytest.fixture
def no_llm(monkeypatch):
    async def _no_shift(q):
        return None, 0.0, None

    async def _no_classification(prompt, labels, fallback_label="unknown"):
        return fallback_label, None, True

    monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", _no_shift)
    monkeypatch.setattr(classify_node, "classify_intent_structured", _no_classification)
    monkeypatch.setattr(classify_node.slot_store, "get_slots", lambda ns, c, v: None)
    monkeypatch.setattr(leave_slot_service, "get_manager_action", lambda c, v: None)
    monkeypatch.setattr(leave_slot_service, "get_report_state", lambda c, v: None)


@pytest.mark.parametrize("query", ["calgary weather", "current temperature in Delhi",
                                   "what time is it in calgary", "weather"])
async def test_a_manager_is_never_sent_to_the_employee_search(no_llm, query):
    out = await classify_node.classify_node(
        {"query": query, "company_id": 1, "conversation_id": "live", "bearer_token": "t",
         "usage_events": [], "is_manager": True, "is_manager_jwt": True, "is_hr_role": False,
         "last_intent": None}, lambda e: None)
    assert out["intent"] == "non_hr"


async def test_non_hr_node_answers_live_without_the_llm_or_search(calgary, monkeypatch):
    import services.hr_graph as hr_graph
    monkeypatch.setattr(live_info, "_fetch_weather",
                        AsyncMock(return_value=_weather(datetime.now(live_info.ZoneInfo(
                            "America/Edmonton")).strftime("%Y-%m-%dT%H:%M"))))
    llm = AsyncMock(side_effect=AssertionError("the LLM must not answer live weather"))
    monkeypatch.setattr(hr_graph, "_call_llm_stream", llm)
    events = []
    await hr_graph.non_hr_node({"query": "current weather in calgary", "intent": "non_hr",
                                "usage_events": [], "context": []}, events.append)
    done = [e for e in events if e.get("type") == "done"][-1]
    assert done["data"]["live_info"] == "weather"
    assert done["data"]["observed_at"] and done["data"]["stale"] is False
    assert "Current weather in Calgary" in done["data"]["answer"]


# -- everything else live: dated, or said to be undated -----------------------

def test_the_model_is_told_search_results_are_snapshots():
    prompt = ai_service.GENERAL_CHAT_WEB_SEARCH_PROMPT
    assert "SNAPSHOTS" in prompt and "Never call something \"current\"" in prompt
    assert "cannot tell how recent" in prompt
    context = ai_service._format_race_search_context([{"title": "t", "url": "u", "content": "c"}])
    assert "NOT live data" in context


def test_the_model_gets_utc_to_judge_age():
    import services.hr_graph as hr_graph
    line = hr_graph._general_chat_clock_line()
    assert " UTC on " in line and "not necessarily the user's" in line


# -- a bare city name ------------------------------------------------------------

async def test_a_city_is_a_known_place_only_by_exact_name_and_size(monkeypatch):
    class Resp:
        def __init__(self, results):
            self._r = results

        def raise_for_status(self):
            pass

        def json(self):
            return {"results": self._r}

    class Client:
        def __init__(self, results):
            self.results = results

        async def __aenter__(self):
            return self

        async def __aexit__(self, *a):
            return False

        async def get(self, url, params=None):
            return Resp(self.results)

    monkeypatch.setattr(live_info.httpx, "AsyncClient", lambda timeout=None: Client([CALGARY]))
    assert await live_info.is_known_place("Calgary") is True
    assert await live_info.is_known_place("Calg") is False
    small = {**CALGARY, "name": "Ananya", "population": 900}
    monkeypatch.setattr(live_info.httpx, "AsyncClient", lambda timeout=None: Client([small]))
    assert await live_info.is_known_place("Ananya") is False


# -- Oct 15: dates, Hinglish, follow-ups, language ------------------------------
#
# "1 Nov 2026 ko Calgary weather" fell to the chat model and came back in
# Korean ("ko"); after "Which city would you like the weather for?", "noida"
# was answered as an encyclopedia question.

from datetime import date  # noqa: E402

TODAY = date(2026, 10, 15)


@pytest.mark.parametrize("query,kind,place,day", [
    ("1 Nov 2026 ko Calgary weather", "weather", "Calgary", date(2026, 11, 1)),
    ("calgary weather tomorrow", "weather", "calgary", date(2026, 10, 16)),
    ("weather in calgary on 20 oct", "weather", "calgary", date(2026, 10, 20)),
    ("weather in calgary yesterday", "weather", "calgary", date(2026, 10, 14)),
    ("delhi ka mausam kaisa hai", "weather", "delhi", None),
    ("aaj noida ka mausam", "weather", "noida", None),
    ("current weather in calgary", "weather", "calgary", None),
    ("what time is it in calgary", "time", "calgary", None),
])
def test_parse(query, kind, place, day):
    parsed = live_info.parse(query, None, TODAY)
    assert (parsed["kind"], parsed["place"], parsed["day"]) == (kind, place, day)


@pytest.mark.parametrize("query", ["apply leave for tomorrow", "show my attendance for 1 nov",
                                   "1 nov ko meri leave hai kya"])
def test_parse_leaves_hr_alone(query):
    assert live_info.parse(query, None, TODAY) is None


ASKED = [{"role": "user", "content": "what's the weather today"},
         {"role": "assistant", "content": 'Which city would you like the weather for? '
                                          '(e.g. "weather in Calgary")'}]
ANSWERED = [{"role": "user", "content": "weather in calgary"},
            {"role": "assistant", "content": "**Current conditions in Calgary, Alberta, Canada** (as of"}]


@pytest.mark.parametrize("reply,context,expected", [
    ("noida", ASKED, ("weather", "noida", None)),
    ("in noida", ASKED, ("weather", "noida", None)),
    ("what about delhi?", ANSWERED, ("weather", "delhi", None)),
    ("and tomorrow?", ANSWERED, ("weather", "calgary", date(2026, 10, 16))),
    ("how about noida tomorrow", ANSWERED, ("weather", "noida", date(2026, 10, 16))),
    ("and london?", [{"role": "user", "content": "time in calgary"},
                     {"role": "assistant", "content": "It's 3:34 AM on Thursday, 15 October 2026 "
                                                      "in Calgary, Alberta, Canada (MDT, UTC−6)."}],
     ("time", "london", None)),
])
def test_follow_ups(reply, context, expected):
    parsed = live_info.parse(reply, context, TODAY)
    assert (parsed["kind"], parsed["place"], parsed["day"]) == expected


def test_a_follow_up_after_a_follow_up_keeps_the_latest_city():
    """"and tomorrow?" after "what about delhi?" is Delhi, not Calgary."""
    context = ANSWERED + [{"role": "user", "content": "what about delhi?"},
                          {"role": "assistant", "content": "**Current conditions in Delhi, India**"}]
    assert live_info.parse("and tomorrow?", context, TODAY)["place"] == "delhi"


@pytest.mark.parametrize("reply,context", [
    ("thanks", ANSWERED), ("ok", ANSWERED), ("show my leave balance", ASKED),
    ("noida", []),                                   # nothing asked: not a follow-up
    ("noida", [{"role": "assistant", "content": "Here is your leave balance"}]),
])
def test_not_a_follow_up(reply, context):
    assert live_info.parse(reply, context, TODAY) is None


async def test_too_far_ahead_is_said_plainly_never_guessed(calgary, monkeypatch):
    fetch = AsyncMock(side_effect=AssertionError("no lookup beyond the forecast range"))
    monkeypatch.setattr(live_info, "_fetch_weather", fetch)
    now = datetime(2026, 10, 15, 12, 0, tzinfo=timezone.utc)
    result = await live_info.weather_answer("Calgary", now_utc=now, day=date(2026, 11, 1))
    assert result["available"] is False
    assert "forecasts only go up to 15 days ahead" in result["answer"]
    assert "Sunday, 1 November 2026" in result["answer"] and "17 days away" in result["answer"]


async def test_a_day_ahead_is_a_labelled_forecast(calgary, monkeypatch):
    monkeypatch.setattr(live_info, "_fetch_weather", AsyncMock(return_value={"daily": {
        "weather_code": [3], "temperature_2m_max": [22.0], "temperature_2m_min": [1.0],
        "precipitation_probability_max": [10], "wind_speed_10m_max": [13.0]}}))
    now = datetime(2026, 10, 15, 12, 0, tzinfo=timezone.utc)
    result = await live_info.weather_answer("Calgary", now_utc=now, day=date(2026, 10, 16))
    assert result["answer"].startswith("**Forecast for Calgary, Alberta, Canada on Friday, "
                                       "16 October 2026** (1 day ahead - forecasts can still change)")
    assert result["forecast"] is True


async def test_a_past_day_is_recorded_weather_from_the_archive_when_old(calgary, monkeypatch):
    fetch = AsyncMock(return_value={"daily": {
        "weather_code": [51], "temperature_2m_max": [17.0], "temperature_2m_min": [10.0],
        "precipitation_sum": [1.2], "wind_speed_10m_max": [9.0]}})
    monkeypatch.setattr(live_info, "_fetch_weather", fetch)
    now = datetime(2026, 10, 15, 12, 0, tzinfo=timezone.utc)
    result = await live_info.weather_answer("Calgary", now_utc=now, day=date(2026, 1, 1))
    assert result["answer"].startswith("**Recorded weather for Calgary")
    assert fetch.call_args.args[1] == live_info._ARCHIVE_URL


def test_the_reply_language_is_hinglish_for_hinglish():
    # Product decision, 29 Oct (HAI-GEN-30): Hinglish gets a Hinglish reply.
    for prompt in (ai_service.GENERAL_CHAT_SYSTEM_PROMPT,
                   ai_service.GENERAL_CHAT_WEB_SEARCH_PROMPT):
        assert "reply in English" in prompt and "gets a Hinglish reply" in prompt


async def test_noida_after_the_city_question_is_not_an_employee_search(no_llm):
    out = await classify_node.classify_node(
        {"query": "noida", "company_id": 1, "conversation_id": "live", "bearer_token": "t",
         "usage_events": [], "is_manager": True, "is_manager_jwt": True, "is_hr_role": False,
         "last_intent": "non_hr", "context": ASKED}, lambda e: None)
    assert out["intent"] == "non_hr"


# -- QA run, Oct 15 (TC-19, TC-25..28, TC-31) -----------------------------------
# TC-28: "calgary ka mausam abhi kaisa hai" ("abhi" = now) matched nothing and
# went to the web-search model, which said "the search results you provided".
# TC-19: "current weather in springfield" was silently Springfield, Missouri.

@pytest.mark.parametrize("query,place,day", [
    ("calgary ka mausam abhi kaisa hai", "calgary", None),
    ("abhi calgary mein mausam kaisa hai", "calgary", None),
    ("delhi ka temperature kitna hai", "delhi", None),
    ("what was the weather in calgary yesterday", "calgary", date(2026, 10, 14)),
    ("weather in calgary tomorrow", "calgary", date(2026, 10, 16)),
    ("weather in calgary on 13 october", "calgary", date(2026, 10, 13)),
])
def test_qa_oct15_questions_are_live(query, place, day):
    parsed = live_info.parse(query, None, TODAY)
    assert parsed and (parsed["kind"], parsed["place"], parsed["day"]) == ("weather", place, day)


def _springfield(admin1, population, tz="America/Chicago"):
    return {"name": "Springfield", "admin1": admin1, "country": "United States",
            "latitude": 37.2, "longitude": -93.3, "timezone": tz, "population": population}


SPRINGFIELDS = [_springfield("Missouri", 170188),
                _springfield("Massachusetts", 154341, "America/New_York"),
                _springfield("Illinois", 114394), _springfield("Ohio", 59680, "America/New_York")]


def _geocoder(results_by_name, monkeypatch):
    class Resp:
        def __init__(self, results): self._r = results
        def raise_for_status(self): pass
        def json(self): return {"results": self._r}

    class Client:
        def __init__(self, *a, **k): pass
        async def __aenter__(self): return self
        async def __aexit__(self, *a): return False
        async def get(self, url, params=None):
            return Resp(results_by_name.get(params["name"].lower(), []))

    monkeypatch.setattr(live_info.httpx, "AsyncClient", Client)


async def test_an_ambiguous_city_is_asked_about_not_guessed(monkeypatch):
    _geocoder({"springfield": SPRINGFIELDS}, monkeypatch)
    fetch = AsyncMock()
    monkeypatch.setattr(live_info, "_fetch_weather", fetch)
    result = await live_info.weather_answer("springfield", now_utc=ASKED_AT)
    assert result["answer"].startswith('There\'s more than one "Springfield"')
    for state in ("Missouri", "Massachusetts", "Illinois"):
        assert state in result["answer"]
    assert "Ohio" not in result["answer"]  # a third the size - not a real contender
    assert not result["available"] and not fetch.called


async def test_a_region_settles_the_ambiguity(monkeypatch):
    _geocoder({"springfield": SPRINGFIELDS}, monkeypatch)
    geo = await live_info._geocode("springfield, massachusetts")
    assert geo["admin1"] == "Massachusetts" and not geo.get("alternatives")


async def test_one_dominant_city_is_not_ambiguous(monkeypatch):
    small_london = {**CALGARY, "name": "London", "admin1": "Ontario", "population": 383822}
    # Real London is a national capital (PPLC) - that is what makes it dominate
    # London, Ontario even though Ontario's is a big city (see BIG_CITY_RIVAL_POPULATION).
    big_london = {**CALGARY, "name": "London", "admin1": "England",
                  "country": "United Kingdom", "population": 8961989, "feature_code": "PPLC"}
    _geocoder({"london": [small_london, big_london]}, monkeypatch)
    geo = await live_info._geocode("london")
    assert geo["admin1"] == "England" and not geo.get("alternatives")


async def test_an_exact_name_beats_a_bigger_partial_one(monkeypatch):
    island = {**CALGARY, "name": "Vancouver Island", "population": 870297}
    city = {**CALGARY, "name": "Vancouver", "population": 600000}
    _geocoder({"vancouver": [island, city]}, monkeypatch)
    assert (await live_info._geocode("vancouver"))["name"] == "Vancouver"


async def test_time_is_asked_about_only_when_the_clocks_differ(monkeypatch):
    _geocoder({"springfield": SPRINGFIELDS}, monkeypatch)
    result = await live_info.time_answer("springfield", now_utc=ASKED_AT)
    assert result["answer"].startswith("There's more than one") and 'e.g. "time in' in result["answer"]
    _geocoder({"springfield": [SPRINGFIELDS[0], SPRINGFIELDS[2]]}, monkeypatch)
    result = await live_info.time_answer("springfield", now_utc=ASKED_AT)
    assert result["available"] and result["answer"].startswith("It's ")


@pytest.mark.parametrize("reply,place", [
    ("missouri", "Springfield, missouri"),
    ("Springfield, Massachusetts", "Springfield, Massachusetts"),
    ("the one in illinois", "Springfield, illinois"),
])
def test_the_reply_to_which_one_keeps_the_question_and_its_day(reply, place):
    asked = ('There\'s more than one "Springfield" - Springfield, Missouri, United States; '
             'or Springfield, Illinois, United States. Which one did you mean? '
             '(e.g. "weather in Springfield, Missouri")')
    context = [{"role": "user", "content": "weather in springfield tomorrow"},
               {"role": "assistant", "content": asked}]
    parsed = live_info.parse(reply, context, TODAY)
    assert parsed == {"kind": "weather", "place": place, "day": date(2026, 10, 16),
                      "day_text": "tomorrow"}


def test_the_model_never_mentions_search_results_to_the_user():
    # TC-31: "the search results you provided" - the user provided nothing.
    assert "the results you provided" in ai_service.GENERAL_CHAT_WEB_SEARCH_PROMPT
    context = ai_service._format_race_search_context([{"title": "t", "url": "u", "content": "c"}])
    assert "cannot see them" in context


# -- Oct 15 (2): "what is weather toaday" / "what is temperature today" ---------
#
# Live: 'I couldn't find a place called "toaday"' and '... called "what is"'.
# A misspelt day is the day; a question with no city asks for the city; a
# place that is not recognised asks for the city and country - and the next
# reply is read as the answer.

@pytest.mark.parametrize("query,day_text", [
    ("what is weather toaday", "today"), ("what is temperature today", "today"),
    ("how is weather today", "today"), ("show me weather today", "today"),
    ("todai ka mausam", "today"),
])
def test_no_city_named(query, day_text):
    parsed = live_info.parse(query, None, TODAY)
    assert (parsed["kind"], parsed["place"], parsed["day_text"]) == ("weather", None, day_text)


@pytest.mark.parametrize("query,place,day", [
    ("what is the weather tommorow in delhi", "delhi", date(2026, 10, 16)),
    ("weather in calgary tmrw", "calgary", date(2026, 10, 16)),
    ("delhi weather toady", "delhi", None),
    ("what is temperature in delhi", "delhi", None),
])
def test_misspelt_days(query, place, day):
    parsed = live_info.parse(query, None, TODAY)
    assert (parsed["place"], parsed["day"]) == (place, day)


@pytest.mark.parametrize("word", ["what is", "how is", "tell me", "show"])
def test_a_question_is_never_a_place(word):
    assert live_info._clean_place(word) is None


async def test_an_unrecognised_place_asks_for_the_city_and_country(monkeypatch):
    monkeypatch.setattr(live_info, "_geocode", AsyncMock(return_value=None))
    weather = (await live_info.weather_answer("xyzqwv"))["answer"]
    assert weather.startswith("Which city would you like the weather for?")
    assert "city and country" in weather and "couldn't find" not in weather
    time = (await live_info.time_answer("xyzqwv"))["answer"]
    assert time.startswith("Which city would you like the time for?")


async def test_a_lookup_outage_is_not_blamed_on_the_spelling(monkeypatch):
    monkeypatch.setattr(live_info, "_geocode", AsyncMock(side_effect=OSError("down")))
    answer = (await live_info.time_answer("calgary"))["answer"]
    assert "right now" in answer and "Which city" not in answer


def test_the_reply_after_asking_for_city_and_country_is_the_answer():
    context = [{"role": "user", "content": "weather in xyzqwv"},
               {"role": "assistant", "content": live_info._ask_for_city("weather", "xyzqwv")}]
    assert live_info.parse("noida, india", context, TODAY)["place"] == "noida, india"
    time_context = [{"role": "user", "content": "time in xyzqwv"},
                    {"role": "assistant", "content": live_info._ask_for_city("time", "xyzqwv")}]
    assert live_info.parse("london", time_context, TODAY)["kind"] == "time"


def test_the_day_asked_about_is_kept_through_the_city_question():
    context = [{"role": "user", "content": "what is the weather tommorow"},
               {"role": "assistant", "content": 'Which city would you like the weather for? '
                                                '(e.g. "weather in Calgary")'}]
    parsed = live_info.parse("delhi", context, TODAY)
    assert (parsed["place"], parsed["day"]) == ("delhi", date(2026, 10, 16))


# -- A place on its own: live snapshot, then the overview (Oct 16) ---------------

CANADA = {"name": "Canada", "feature_code": "PCLI", "country": "Canada", "population": 37058856,
          "latitude": 60.1, "longitude": -113.6, "timezone": None}
CALGARY_GEO = {**CALGARY, "feature_code": "PPL", "elevation": 1048.0}


class _GeoClient:
    """httpx.AsyncClient stand-in answering the geocoder by searched name."""
    by_name = {"calgary": [CALGARY_GEO], "canada": [CANADA], "alberta": []}

    def __init__(self, timeout=None):
        pass

    async def __aenter__(self):
        return self

    async def __aexit__(self, *a):
        return False

    async def get(self, url, params=None):
        results = self.by_name.get((params or {}).get("name", "").lower(), [])

        class R:
            def raise_for_status(self):
                pass

            def json(self):
                return {"results": results}
        return R()


@pytest.mark.parametrize("text,bare", [
    ("canada calgary alberta", True), ("Calgary Alberta Canada", True), ("Delhi", True),
    ("Calgary, Canada", True), ("what is calgary known for", False),
    ("weather in calgary", False), ("history of canada", False),
])
def test_looks_like_bare_place(text, bare):
    assert live_info.looks_like_bare_place(text) is bare


@pytest.mark.parametrize("text,name", [
    ("canada calgary alberta", "Calgary"), ("Calgary Alberta Canada", "Calgary"),
    ("Calgary, Canada", "Calgary"), ("Calgary", "Calgary"), ("Canada", "Canada"),
])
async def test_resolve_place_in_any_order(monkeypatch, text, name):
    monkeypatch.setattr(live_info.httpx, "AsyncClient", _GeoClient)
    assert (await live_info.resolve_place(text))["name"] == name


async def test_resolve_place_needs_a_real_match(monkeypatch):
    monkeypatch.setattr(live_info.httpx, "AsyncClient", _GeoClient)
    assert await live_info.resolve_place("machine learning") is None
    assert await live_info.resolve_place("canada brad pitt") is None


async def test_a_city_snapshot_has_the_live_facts(monkeypatch):
    monkeypatch.setattr(live_info, "_fetch_weather", AsyncMock(return_value=_weather("2026-10-14T12:15")))
    text = await live_info.place_snapshot(CALGARY_GEO, now_utc=ASKED_AT)
    assert text.startswith("**Calgary, Alberta, Canada - right now**")
    assert "Local time: 12:18 PM, Wednesday, 14 October 2026 (MDT, UTC−6)" in text
    assert "Weather: 11.5 °C, mainly clear" in text and "as of 12:15 PM" in text
    assert "Today's forecast: high 15 °C, low 3 °C" in text
    assert "Population: about 1,306,784" in text


async def test_a_stale_reading_is_left_out_of_the_snapshot(monkeypatch):
    monkeypatch.setattr(live_info, "_fetch_weather", AsyncMock(return_value=_weather("2026-10-13T17:00")))
    text = await live_info.place_snapshot(CALGARY_GEO, now_utc=ASKED_AT)
    assert "11.5" not in text and "out of date" in text


async def test_a_country_snapshot_has_no_weather(monkeypatch):
    fetch = AsyncMock(side_effect=AssertionError("no weather for a whole country"))
    monkeypatch.setattr(live_info, "_fetch_weather", fetch)
    text = await live_info.place_snapshot(CANADA, now_utc=ASKED_AT)
    assert "spans several time zones" in text and "Population: about 37,058,856" in text


async def test_non_hr_node_leads_with_the_snapshot(monkeypatch):
    import services.hr_graph as hr_graph
    monkeypatch.setattr(live_info, "resolve_place", AsyncMock(return_value=CALGARY_GEO))
    monkeypatch.setattr(live_info, "place_snapshot", AsyncMock(return_value="**Calgary - right now**"))
    seen = {}

    async def fake_stream(messages, max_tokens=None, use_tools=True):
        seen["system"] = messages[0]["content"]
        yield {"type": "chunk", "content": "Calgary is a city 【Calgary - Wikipedia】."}

    monkeypatch.setattr(hr_graph, "_call_llm_stream", fake_stream)
    events = []
    await hr_graph.non_hr_node({"query": "canada calgary alberta", "intent": "non_hr",
                                "usage_events": [], "context": []}, events.append)
    answer = [e for e in events if e.get("type") == "done"][-1]["data"]["answer"]
    assert answer.startswith("**Calgary - right now**\n\n")
    assert "(Calgary - Wikipedia)" in answer and "【" not in answer
    assert "do not give any time, temperature or weather figure of your own" in seen["system"]
