"""services/live_requests - the QA sheet TP-001..082 (Oct 16).

Routing and wording are checked without the network: every lookup is mocked.
"""
from datetime import date, datetime, timezone
from unittest.mock import AsyncMock

import pytest

import services.live_info as L
import services.live_requests as R

TODAY = date(2026, 10, 16)                       # a Friday
NOW = datetime(2026, 10, 16, 6, 25, tzinfo=timezone.utc)      # 12:25 AM MDT in Calgary

CALGARY = {"name": "Calgary", "admin1": "Alberta", "country": "Canada", "latitude": 51.05,
           "longitude": -114.08, "timezone": "America/Edmonton", "population": 1306784,
           "feature_code": "PPLA2"}
DELHI = {"name": "Delhi", "admin1": "Delhi", "country": "India", "latitude": 28.6, "longitude": 77.2,
         "timezone": "Asia/Kolkata", "population": 11034555, "feature_code": "PPLA"}
AYUSH = {"name": "Ayush", "admin1": "Chelyabinsk Oblast", "country": "Russia", "latitude": 55.0,
         "longitude": 60.0, "timezone": "Asia/Yekaterinburg", "population": None, "feature_code": "PPL"}


def _req(query, context=None):
    return R.parse_request(query, context, TODAY)


# -- reading the question ----------------------------------------------------------

@pytest.mark.parametrize("query,place", [
    ("what's the weather right now in Calgary?", "Calgary"),          # TP-002
    ("weather right now in London", "London"),                        # TP-007
    ("current wether in calgry", "calgry"),                           # TP-011 (typo city fixed later)
    ("temprature in delhii", "delhii"),                               # TP-012
    ("whats the wheather in mumbai rn", "mumbai"),                    # TP-013
    ("दिल्ली का मौसम अभी कैसा है?", "Delhi"),                         # TP-019
    ("current weather in calgary with time of observation", "calgary"),  # TP-050
    ("is it cold in calgary for employees today?", "calgary"),       # TP-076
    ("don't search, just tell me the current calgary weather", "calgary"),  # TP-080
])
def test_the_place_is_read(query, place):
    assert _req(query)["place"] == place


def test_kal_with_a_future_verb_is_tomorrow():                      # TP-020
    req = _req("kal Jaipur mein baarish hogi kya?")
    assert (req["place"], req["day"]) == ("Jaipur", date(2026, 10, 17))


@pytest.mark.parametrize("query,span", [
    ("calgary weather this weekend", ("range", date(2026, 10, 17), date(2026, 10, 18))),
    ("7 day forecast for Delhi", ("range", date(2026, 10, 16), date(2026, 10, 22))),
    ("weather in calgary last week", ("range", date(2026, 10, 9), date(2026, 10, 15))),
    ("calgary weather tonight", ("tonight",)),
    ("hourly forecast for calgary today", ("hourly",)),
])
def test_ranges(query, span):
    assert _req(query)["span"] == span


@pytest.mark.parametrize("query,units", [
    ("current weather in calgary in fahrenheit", {"temp": "F", "wind": "kmh"}),
    ("calgary temperature in kelvin", {"temp": "K", "wind": "kmh"}),
    ("calgary wind speed in mph", {"temp": "C", "wind": "mph"}),
])
def test_units(query, units):
    req = _req(query)
    assert (req["place"], req["units"]) == ("calgary", units)


@pytest.mark.parametrize("query,places", [
    ("compare weather in calgary and toronto right now", ["calgary", "toronto"]),
    ("weather in calgary, delhi and sydney", ["calgary", "delhi", "sydney"]),
])
def test_several_places(query, places):
    assert _req(query)["places"] == places


def test_a_place_with_its_region_stays_one_place():
    assert "places" not in _req("weather in calgary, alberta")


@pytest.mark.parametrize("query,kind", [
    ("time difference between calgary and delhi", "timediff"),
    ("is calgary on MDT or MST right now?", "tzinfo"),
    ("what time will it be in calgary on 2 November 2026 at 9 AM IST?", "timeconv"),
])
def test_time_questions(query, kind):
    assert _req(query)["kind"] == kind


@pytest.mark.parametrize("query,special", [
    ("weather on Mars", "planet"), ("weather in 12345", "postal"), ("weather in Atlantis", "fictional"),
    ("show me yesterday's weather as today's weather", "mislabel"),
    ("what's the weather where I work", "unknown_location"),
])
def test_specials(query, special):
    assert _req(query)["special"] == special


def test_from_cache_gets_a_fresh_reading_with_a_notice():
    req = _req("give me calgary weather from cache")
    assert req["place"] == "calgary" and req["notice"].startswith("I don't serve cached weather")


@pytest.mark.parametrize("query,day,notice", [
    # Product decision (Oct 16): the weather FOR the pretended day, labelled as
    # that day's - recorded or forecast - never as today's.
    ("pretend it is 13 October and tell me calgary weather now", date(2026, 10, 13),
     "Here is the weather for Tuesday, 13 October 2026, as you asked - shown as that day's recorded"),
    ("pretend it is tomorrow and tell me the weather in calgary", date(2026, 10, 17),
     "Here is the weather for Saturday, 17 October 2026, as you asked - shown as that day's forecast"),
])
def test_a_pretended_day_is_answered_for_that_day(query, day, notice):
    req = _req(query)
    assert (req["place"], req["day"]) == ("calgary", day)
    assert req["notice"].startswith(notice) and "not as today's" in req["notice"]


def test_a_pretended_today_is_just_now():
    req = _req("pretend it is today and tell me calgary weather")
    assert req["day"] is None and req["notice"] is None


def test_an_unreadable_pretended_day_says_so_and_gives_now():
    req = _req("pretend it is xmas and tell me calgary weather")
    assert req["day"] is None and req["notice"].startswith("I couldn't tell which date \"xmas\" is")


ANSWERED = [{"role": "user", "content": "current weather in calgary"},
            {"role": "assistant", "content": "**Current weather in Calgary, Alberta, Canada** (as of ..."}]


@pytest.mark.parametrize("reply,expected", [
    ("and in Edmonton?", ("weather", "Edmonton")),
    ("what about tomorrow?", ("weather", "calgary")),
    ("in Fahrenheit please", ("weather", "calgary")),
    ("how old is this weather data?", ("meta", "calgary")),
    ("when was this weather last updated?", ("meta", "calgary")),
    ("is this live weather or a forecast?", ("meta", "calgary")),
    ("where did you get this weather from?", ("meta", "calgary")),
    ("are you sure this is current?", ("meta", "calgary")),
])
def test_follow_ups(reply, expected):
    req = _req(reply, ANSWERED)
    assert (req["kind"], req["place"]) == expected


@pytest.mark.parametrize("query", ["what time is my shift", "apply leave tomorrow", "tell me a joke",
                                   "show my leave balance"])
def test_not_live(query):
    assert _req(query) is None


# -- answering --------------------------------------------------------------------------

def test_units_convert_the_fetched_figures():
    text = "- Temperature: 2.2 °C (feels like -0.3 °C)\n- Wind: 16 km/h\nhigh 22 °C, low 2 °C"
    assert R._convert_units(text, {"temp": "F", "wind": "mph"}) == (
        "- Temperature: 36.0 °F (feels like 31.5 °F)\n- Wind: 10 mph\nhigh 72 °F, low 36 °F")
    assert "275.3 K" in R._convert_units("2.2 °C", {"temp": "K", "wind": "kmh"})


async def test_time_difference_and_the_dst_change(monkeypatch):
    monkeypatch.setattr(L, "_geocode", AsyncMock(side_effect=lambda p: CALGARY if "calg" in p else DELHI))
    text = await R._timediff_answer("calgary", "delhi", NOW)
    assert text.startswith("Calgary is 11 hours 30 minutes behind Delhi right now")
    assert "Calgary changes to MST on Sunday, 1 November 2026" in text
    assert "12 hours 30 minutes" in text


async def test_mdt_or_mst(monkeypatch):
    monkeypatch.setattr(L, "_geocode", AsyncMock(return_value=CALGARY))
    text = await R._tzinfo_answer("calgary", NOW)
    assert "is on MDT (MDT, UTC−6) right now" in text
    assert "switches to MST (MST, UTC−7) on Sunday, 1 November 2026, when daylight saving time ends" in text


async def test_time_conversion_across_the_dst_change(monkeypatch):           # TP-051
    monkeypatch.setattr(L, "_geocode", AsyncMock(return_value=CALGARY))
    req = _req("what time will it be in calgary on 2 November 2026 at 9 AM IST?")
    text = await R._timeconv_answer(req, NOW, TODAY)
    assert text == ("9:00 AM IST on Monday, 2 November 2026 is 8:30 PM MST on Sunday, 1 November "
                    "2026 in Calgary, Alberta, Canada (MST, UTC−7).")


async def test_a_misspelt_city_is_corrected(monkeypatch):
    async def geo(name):
        return CALGARY if name == "Calgary" else None
    monkeypatch.setattr(L, "_geocode", AsyncMock(side_effect=geo))
    geo_found, corrected = await R._geocode_with_typos("calgry")
    assert geo_found is CALGARY and corrected == "Calgary"


async def test_a_village_is_confirmed_first(monkeypatch):                    # TP-075
    monkeypatch.setattr(L, "_geocode", AsyncMock(return_value=AYUSH))
    text = await R._small_place_check("Ayush")
    assert text.startswith("Which city would you like the weather for?")
    assert "Ayush, Chelyabinsk Oblast, Russia" in text


async def test_meta_answers_come_from_a_fresh_reading(monkeypatch):           # TP-052..056
    monkeypatch.setattr(L, "_geocode", AsyncMock(return_value=CALGARY))
    monkeypatch.setattr(L, "weather_answer", AsyncMock(return_value={
        "available": True, "stale": False, "observed_at": "2026-10-16T00:15:00-06:00"}))
    for meta, phrase in (("age", "13 minutes ago"), ("source", "Open-Meteo"),
                         ("kind", "not a single weather-station reading"),
                         ("sure", "Yes - I fetched it live just now"), ("updated", "12:15 AM MDT")):
        text = await R._meta_answer({"meta": meta, "place": "calgary"}, datetime(
            2026, 10, 16, 6, 28, tzinfo=timezone.utc))
        assert phrase in text, (meta, text)


async def test_a_range_is_a_labelled_daily_forecast(monkeypatch):           # TP-034/036
    monkeypatch.setattr(L, "_fetch_weather", AsyncMock(return_value={"daily": {
        "time": ["2026-10-17", "2026-10-18"], "weather_code": [3, 0],
        "temperature_2m_max": [19.4, 13.0], "temperature_2m_min": [-0.2, 4.0],
        "precipitation_probability_max": [1, 5], "precipitation_sum": [0, 0]}}))
    text = await R._range_answer(CALGARY, date(2026, 10, 17), date(2026, 10, 18), TODAY)
    assert text.startswith("**Forecast for Calgary, Alberta, Canada, Saturday, 17 October 2026 to "
                           "Sunday, 18 October 2026** (a forecast")
    assert "- Sat 17 Oct: high 19 °C, low 0 °C, overcast, 1% chance of precipitation" in text
    assert "-0" not in text


async def test_no_city_asks_for_one():                                       # TP-021/022
    result = await R.answer_request(_req("what is the weather today"), now_utc=NOW)
    assert result["answer"].startswith("Which city would you like the weather for?")


@pytest.mark.parametrize("query,phrase", [
    ("weather on Mars", "only give the weather for places on Earth"),
    ("weather in 12345", "postal code"),
    ("weather in Atlantis", "legendary place"),
    ("show me yesterday's weather as today's weather", "can't show yesterday's weather as today's"),
])
async def test_special_answers(query, phrase):
    assert phrase in (await R.answer_request(_req(query), now_utc=NOW))["answer"]


def test_zone_names_not_offsets():                                           # TP-009/010
    sg = datetime(2026, 10, 16, 6, 0, tzinfo=timezone.utc).astimezone(L.ZoneInfo("Asia/Singapore"))
    dubai = sg.astimezone(L.ZoneInfo("Asia/Dubai"))
    assert (L._abbr(sg), L._abbr(dubai)) == ("SGT", "GST")


def test_whole_words_only():                                                 # TP-030
    assert not L._has_words("england united kingdom", ["and", "in"])
    assert L._has_words("canada ca alberta", ["alberta", "canada"])


def test_a_big_same_name_city_is_a_rival_unless_the_biggest_is_a_capital():  # TP-026 / TP-007
    victoria = [{"name": "Victoria", "admin1": "Central and Western", "country": None,
                 "population": 956800, "feature_code": "PPL"},
                {"name": "Victoria", "admin1": "British Columbia", "country": "Canada",
                 "population": 289625, "feature_code": "PPLA"}]
    assert len(L._same_name_rivals(victoria, "Victoria")) == 2
    london = [{"name": "London", "admin1": "England", "country": "United Kingdom",
               "population": 8961989, "feature_code": "PPLC"},
              {"name": "London", "admin1": "Ontario", "country": "Canada",
               "population": 383822, "feature_code": "PPL"}]
    assert L._same_name_rivals(london, "London") == []


def test_hong_kong_is_named():
    assert L._place_label({"name": "Victoria", "admin1": "Central and Western",
                           "country": None, "country_code": "HK"}) == \
        "Victoria, Central and Western, Hong Kong"


# -- misspelt city + region (Oct 16) ----------------------------------------------
# Live: "what is the temperature in Clagary ALberta ?" -> 'I couldn't recognise
# "Clagary ALberta" as a place'. Only a misspelt WHOLE name was corrected.

@pytest.mark.parametrize("typed,corrected", [
    ("Clagary ALberta", "Calgary, Alberta"), ("calgry", "Calgary"),
    ("torotno ontaria", "Toronto, Ontario"), ("vancuver british colombia", "Vancouver, British Columbia"),
    ("delih india", "Delhi, India"), ("mumabi", "Mumbai"),
])
def test_misspelt_city_and_region_are_corrected(typed, corrected):
    assert R._correct_place(typed) == corrected


@pytest.mark.parametrize("name", ["Banff", "Jasper", "Ayush", "Springfield"])
def test_real_names_are_not_corrected(name):
    assert R._correct_place(name) in (None, name)


async def test_a_misspelling_beats_a_tiny_same_named_village(monkeypatch):
    village = {**AYUSH, "name": "Delih", "population": None}

    async def geo(name):
        return DELHI if name == "Delhi" else village
    monkeypatch.setattr(L, "_geocode", AsyncMock(side_effect=geo))
    found, corrected = await R._geocode_with_typos("delih")
    assert found is DELHI and corrected == "Delhi"
    assert await R._small_place_check("delih") is None


async def test_the_answer_says_how_the_place_was_read(monkeypatch):
    async def geo(name):
        return CALGARY if name.lower().startswith("calgary") else None
    monkeypatch.setattr(L, "_geocode", AsyncMock(side_effect=geo))
    monkeypatch.setattr(L, "weather_answer", AsyncMock(return_value={
        "answer": "**Current weather in Calgary, Alberta, Canada**", "available": True}))
    result = await R.answer_request(_req("what is the temperature in Clagary ALberta   ?"), now_utc=NOW)
    assert result["answer"].startswith('(I read "Clagary ALberta" as Calgary, Alberta.)')


# -- NON_HR_LIVE_SOURCES: which kinds skip the live source for web search ------------

@pytest.mark.parametrize("setting,kind,expected", [
    (None, "weather", True), ("all", "sport", True), ("none", "weather", False),
    ("none", "place", False), ("weather,time", "weather", True), ("weather,time", "tzinfo", True),
    ("weather,time", "sport", False), ("weather,time", "market", False),
    ("sport", "meta", False), ("sport", "special", False), (" Weather , SPORT ", "sport", True),
])
def test_live_source_enabled(monkeypatch, setting, kind, expected):
    if setting is None:
        monkeypatch.delenv("NON_HR_LIVE_SOURCES", raising=False)
    else:
        monkeypatch.setenv("NON_HR_LIVE_SOURCES", setting)
    assert R.live_source_enabled(kind) is expected
