"""Crypto prices and exchange rates from live sources (Oct 16).

Live: after a weather answer, "bitcoin price right now" got 'I couldn't
recognise "bitcoin price" as a place'; on its own it was answered from a
search snapshot hours old - or, with an empty search, an invented price.
"""
from datetime import datetime, timezone
from unittest.mock import AsyncMock

import pytest

import services.live_markets as M
import services.live_requests as R

NOW = datetime(2026, 10, 16, 7, 12, tzinfo=timezone.utc)
WEATHER = [{"role": "user", "content": "current weather in calgary"},
           {"role": "assistant", "content": "**Current weather in Calgary, Alberta, Canada** (as of ..."}]


@pytest.mark.parametrize("query,expected", [
    ("bitcoin price right now", {"kind": "crypto", "coin": "bitcoin", "currencies": ["USD", "CAD", "INR"]}),
    ("btc price in inr", {"kind": "crypto", "coin": "bitcoin", "currencies": ["INR"]}),
    ("how much is ethereum", {"kind": "crypto", "coin": "ethereum", "currencies": ["USD", "CAD", "INR"]}),
    ("current USD to CAD exchange rate", {"kind": "fx", "base": "USD", "quote": "CAD", "amount": None}),
    ("convert 100 usd to inr", {"kind": "fx", "base": "USD", "quote": "INR", "amount": 100.0}),
    ("dollar to rupee", {"kind": "fx", "base": "USD", "quote": "INR", "amount": None}),
])
def test_parse(query, expected):
    assert M.parse(query) == expected


@pytest.mark.parametrize("query", ["what is sol", "connect the dot", "I want to apply leave",
                                   "weather in calgary"])
def test_not_a_market_question(query):
    assert M.parse(query) is None


def test_after_a_weather_answer_bitcoin_is_bitcoin_not_a_city():
    req = R.parse_request("bitcoin price right now", WEATHER)
    assert req["kind"] == "market" and req["market"]["coin"] == "bitcoin"


@pytest.mark.parametrize("reply", ["gold rate today", "what about the stock market?", "latest news"])
def test_another_topic_after_a_weather_answer_is_not_a_weather_follow_up(reply):
    req = R.parse_request(reply, WEATHER)
    assert req is None or req.get("kind") != "weather"


def test_a_city_after_a_weather_answer_still_is():
    assert R.parse_request("what about mumbai?", WEATHER)["place"] == "mumbai"


def test_and_in_inr_after_a_price_answer():
    context = [{"role": "user", "content": "bitcoin price right now"},
               {"role": "assistant", "content": "**Bitcoin price right now** (as of ...)"}]
    assert M.parse_followup("and in inr?", context) == {
        "kind": "crypto", "coin": "bitcoin", "currencies": ["INR"]}
    assert M.parse_followup("and in inr?", WEATHER) is None


async def test_a_live_price_carries_its_own_time(monkeypatch):
    monkeypatch.setenv("QUOTA_TIMEZONE", "Asia/Kolkata")
    monkeypatch.setattr(M, "_get", AsyncMock(return_value={"bitcoin": {
        "usd": 82077, "usd_24h_change": 1.52, "last_updated_at": int(NOW.timestamp()) - 120}}))
    result = await M.crypto_answer("bitcoin", ["USD"], now_utc=NOW)
    assert result["answer"].startswith("**Bitcoin price right now** (as of 7:10 AM UTC (12:40 PM IST) "
                                       "on 16 October 2026, 2 minutes ago):")
    assert "- $82,077 (+1.52% in the last 24 hours)" in result["answer"]


async def test_an_old_price_is_never_called_current(monkeypatch):
    monkeypatch.setattr(M, "_get", AsyncMock(return_value={"bitcoin": {
        "usd": 82077, "last_updated_at": int(NOW.timestamp()) - 6 * 3600}}))
    result = await M.crypto_answer("bitcoin", ["USD"], now_utc=NOW)
    assert result["stale"] and "right now" not in result["answer"].split("\n")[0]
    assert "may have moved since" in result["answer"]


async def test_no_source_means_no_price(monkeypatch):
    monkeypatch.setattr(M, "_get", AsyncMock(side_effect=OSError("down")))
    result = await M.crypto_answer("bitcoin", ["USD"], now_utc=NOW)
    assert not result["available"] and "won't quote one" in result["answer"]
    assert "$" not in result["answer"]


async def test_an_exchange_rate_is_labelled_as_the_daily_reference_rate(monkeypatch):
    monkeypatch.setattr(M, "_get", AsyncMock(return_value={
        "base": "USD", "date": "2026-10-15", "rates": {"CAD": 1.4207}}))
    result = await M.fx_answer("USD", "CAD", 100)
    assert result["answer"].startswith("**$100.00 = C$142.07** (at 1 USD = 1.4207 CAD)")
    assert "reference rate for Thursday, 15 October 2026" in result["answer"]
    assert "not a live market quote" in result["answer"]
