"""services/live_markets.py

Crypto prices and currency exchange rates, from live sources with their own
timestamps - never from a web-search snippet.

Why (Oct 16): "bitcoin price right now" was answered from race-api's Brave
search, whose results are search-index SNAPSHOTS of price pages (title, url,
snippet - no fetch time). One answer quoted "$82,116 as of 7:36 PM EDT"
6 hours old; another, with an empty search, invented "$27,842 as of 10:30 AM
UTC". A snapshot can never be a current price.

Sources (both free, no key):
  * CoinGecko /simple/price - the price, 24h change and `last_updated_at`.
  * Frankfurter - the European Central Bank's reference rates, published once
    per working day. They are NOT a live market quote, and the answer says
    so, with the date they are for.
If a source cannot be reached the answer says it cannot get the figure now -
it never falls back to a guess.
"""
import logging
import os
import re
from datetime import datetime, timezone
from zoneinfo import ZoneInfo

import httpx

logger = logging.getLogger(__name__)

_COINGECKO_URL = os.getenv("LIVE_CRYPTO_URL", "https://api.coingecko.com/api/v3/simple/price")
_FX_URL = os.getenv("LIVE_FX_URL", "https://api.frankfurter.dev/v1/latest")
_TIMEOUT = float(os.getenv("LIVE_INFO_TIMEOUT_SECONDS", "6"))
#: A crypto price older than this is said to be out of date.
CRYPTO_STALE_MINUTES = int(os.getenv("LIVE_CRYPTO_STALE_MINUTES", "30"))

_COINS = {
    "bitcoin": "bitcoin", "btc": "bitcoin", "ethereum": "ethereum", "eth": "ethereum",
    "ether": "ethereum", "solana": "solana", "sol": "solana", "dogecoin": "dogecoin",
    "doge": "dogecoin", "xrp": "ripple", "ripple": "ripple", "cardano": "cardano",
    "ada": "cardano", "litecoin": "litecoin", "ltc": "litecoin", "bnb": "binancecoin",
    "tether": "tether", "usdt": "tether", "polkadot": "polkadot", "dot": "polkadot",
    "tron": "tron", "trx": "tron", "shiba inu": "shiba-inu", "shib": "shiba-inu",
}
_COIN_NAMES = {"bitcoin": "Bitcoin", "ethereum": "Ethereum", "solana": "Solana",
               "dogecoin": "Dogecoin", "ripple": "XRP", "cardano": "Cardano",
               "litecoin": "Litecoin", "binancecoin": "BNB", "tether": "Tether (USDT)",
               "polkadot": "Polkadot", "tron": "TRON", "shiba-inu": "Shiba Inu"}
# Coin words that are also ordinary English: only a coin next to a price word.
_AMBIGUOUS_COINS = {"sol", "dot", "ada", "ether", "tron"}

_CURRENCIES = {
    "usd": "USD", "dollar": "USD", "dollars": "USD", "us dollar": "USD", "us dollars": "USD",
    "cad": "CAD", "canadian dollar": "CAD", "canadian dollars": "CAD", "inr": "INR",
    "rupee": "INR", "rupees": "INR", "indian rupee": "INR", "indian rupees": "INR", "rs": "INR",
    "eur": "EUR", "euro": "EUR", "euros": "EUR", "gbp": "GBP", "pound": "GBP", "pounds": "GBP",
    "sterling": "GBP", "aud": "AUD", "australian dollar": "AUD", "jpy": "JPY", "yen": "JPY",
    "aed": "AED", "dirham": "AED", "dirhams": "AED", "sgd": "SGD", "singapore dollar": "SGD",
    "chf": "CHF", "swiss franc": "CHF", "cny": "CNY", "yuan": "CNY", "nzd": "NZD", "hkd": "HKD",
    "mxn": "MXN", "zar": "ZAR",
}
_CURRENCY_ALT = "|".join(sorted((re.escape(c) for c in _CURRENCIES), key=len, reverse=True))
_COIN_ALT = "|".join(sorted((re.escape(c) for c in _COINS), key=len, reverse=True))

_PRICE_WORD_RE = re.compile(r"\b(?:price|prices|rate|value|worth|cost|trading|quote|kitna|kitne|"
                            r"bhav|daam|how\s+much)\b", re.IGNORECASE)
_COIN_RE = re.compile(rf"\b(?P<coin>{_COIN_ALT})\b", re.IGNORECASE)
_IN_CURRENCY_RE = re.compile(rf"\b(?:in|to|into)\s+(?P<cur>{_CURRENCY_ALT})\b", re.IGNORECASE)
_FX_PAIR_RE = re.compile(
    rf"(?:(?P<amount>\d+(?:[.,]\d+)?)\s*)?\b(?P<a>{_CURRENCY_ALT})\b\s*(?:to|in|into|/|vs|versus|-)\s*"
    rf"\b(?P<b>{_CURRENCY_ALT})\b", re.IGNORECASE)
_FX_WORD_RE = re.compile(r"\b(?:exchange|rate|convert|conversion|forex|fx|how\s+much|worth|value)\b",
                         re.IGNORECASE)


def parse(query: str):
    """{"kind": "crypto", "coin": id, "currencies": [...]} /
    {"kind": "fx", "base", "quote", "amount"} / None."""
    text = (query or "").strip().replace("’", "'")
    if not text:
        return None
    coin = _COIN_RE.search(text)
    if coin:
        word = coin.group("coin").lower()
        if word not in _AMBIGUOUS_COINS or _PRICE_WORD_RE.search(text):
            if _PRICE_WORD_RE.search(text) or re.search(r"\b(?:now|today|live|current|currently)\b",
                                                       text, re.IGNORECASE) \
                    or len(text.split()) <= 3 or _IN_CURRENCY_RE.search(text):
                cur = _IN_CURRENCY_RE.search(text)
                currencies = [_CURRENCIES[cur.group("cur").lower()]] if cur else ["USD", "CAD", "INR"]
                return {"kind": "crypto", "coin": _COINS[word], "currencies": currencies}
    pair = _FX_PAIR_RE.search(text)
    if pair and (_FX_WORD_RE.search(text) or pair.group("amount") or len(text.split()) <= 5):
        base, quote = _CURRENCIES[pair.group("a").lower()], _CURRENCIES[pair.group("b").lower()]
        if base != quote:
            amount = float(pair.group("amount").replace(",", "")) if pair.group("amount") else None
            return {"kind": "fx", "base": base, "quote": quote, "amount": amount}
    return None


_CURRENCY_FOLLOWUP_RE = re.compile(
    rf"^\s*(?:and\s+|what\s+about\s+|how\s+about\s+)?(?:(?:in|to|into)\s+)?(?P<cur>{_CURRENCY_ALT})"
    rf"(?:\s+please|\s+pls)?\s*[?.!]*\s*$", re.IGNORECASE)


def parse_followup(text: str, context):
    """"and in INR?" right after a crypto price answer: the same coin, in that
    currency - live, it went to the chat model, which converted with a rate
    from a search snippet."""
    m = _CURRENCY_FOLLOWUP_RE.match(text or "")
    if not m or not context:
        return None
    last = next((c.get("content") or "" for c in reversed(context) if c.get("role") == "assistant"), "")
    if " price right now**" not in last and "price I could get is from" not in last:
        return None
    for msg in reversed(context):
        if msg.get("role") == "user":
            earlier = parse(msg.get("content") or "")
            if earlier and earlier.get("kind") == "crypto":
                return {**earlier, "currencies": [_CURRENCIES[m.group("cur").lower()]]}
    return None


def _app_tz():
    try:
        return ZoneInfo(os.getenv("QUOTA_TIMEZONE", "UTC"))
    except Exception:
        return ZoneInfo("UTC")


def _money(value: float, currency: str) -> str:
    symbol = {"USD": "$", "CAD": "C$", "INR": "₹", "EUR": "€", "GBP": "£", "JPY": "¥",
              "AUD": "A$", "SGD": "S$"}.get(currency, "")
    decimals = 2 if value < 1000 else 0
    text = f"{value:,.{decimals}f}"
    return f"{symbol}{text}" if symbol else f"{text} {currency}"


async def _get(url: str, params: dict) -> dict:
    async with httpx.AsyncClient(timeout=_TIMEOUT, follow_redirects=True) as client:
        resp = await client.get(url, params=params)
        resp.raise_for_status()
        return resp.json()


async def crypto_answer(coin: str, currencies, now_utc: datetime | None = None) -> dict:
    now_utc = now_utc or datetime.now(timezone.utc)
    name = _COIN_NAMES.get(coin, coin.title())
    try:
        data = (await _get(_COINGECKO_URL, {
            "ids": coin, "vs_currencies": ",".join(c.lower() for c in currencies),
            "include_last_updated_at": "true", "include_24hr_change": "true"})).get(coin) or {}
        updated = datetime.fromtimestamp(int(data["last_updated_at"]), tz=timezone.utc)
    except Exception as exc:
        logger.warning("[LiveMarkets] crypto price failed for %s: %s", coin, exc)
        return {"available": False, "answer": (
            f"I can't get a live {name} price right now, so I won't quote one - an old figure "
            f"shown as current would be wrong. Please check an exchange or a site such as "
            f"CoinGecko or CoinMarketCap.")}
    minutes = max(0, int((now_utc - updated).total_seconds() // 60))
    local = updated.astimezone(_app_tz())
    when = (f"{updated.strftime('%I:%M %p').lstrip('0')} UTC "
            f"({local.strftime('%I:%M %p').lstrip('0')} {local.tzname()}) on "
            f"{local.strftime('%d %B %Y').lstrip('0')}")
    lines = []
    if minutes > CRYPTO_STALE_MINUTES:
        lines.append(f"**The latest {name} price I could get is from {when}** - about "
                     f"{minutes} minutes old, so it may have moved since.")
    else:
        ago = "just now" if minutes == 0 else f"{minutes} minute{'s' if minutes != 1 else ''} ago"
        lines.append(f"**{name} price right now** (as of {when}, {ago}):")
    for cur in currencies:
        price = data.get(cur.lower())
        if price is None:
            continue
        change = data.get(f"{cur.lower()}_24h_change")
        lines.append(f"- {_money(price, cur)}"
                     + (f" ({change:+.2f}% in the last 24 hours)" if change is not None else ""))
    lines.append("\nCrypto prices move constantly, and each exchange quotes a slightly different "
                 "figure.")
    return {"available": True, "answer": "\n".join(lines), "observed_at": updated.isoformat(),
            "stale": minutes > CRYPTO_STALE_MINUTES, "source": "CoinGecko"}


async def fx_answer(base: str, quote: str, amount: float | None = None) -> dict:
    try:
        data = await _get(_FX_URL, {"base": base, "symbols": quote})
        rate = float((data.get("rates") or {})[quote])
        day = datetime.fromisoformat(str(data["date"]))
    except Exception as exc:
        logger.warning("[LiveMarkets] fx rate failed for %s/%s: %s", base, quote, exc)
        return {"available": False, "answer": (
            f"I can't get the {base} to {quote} exchange rate right now, so I won't quote one. "
            f"Please check your bank or a currency converter.")}
    when = day.strftime("%A, %d %B %Y").replace(" 0", " ")
    lines = []
    if amount is not None:
        lines.append(f"**{_money(amount, base)} = {_money(amount * rate, quote)}** "
                     f"(at 1 {base} = {rate:,.4f} {quote})")
    else:
        lines.append(f"**1 {base} = {rate:,.4f} {quote}** (1 {quote} = {1 / rate:,.4f} {base})")
    lines.append(f"\nThis is the European Central Bank's reference rate for {when}. It is "
                 f"published once each working day - not a live market quote - and your bank or "
                 f"card provider will charge a slightly different rate.")
    return {"available": True, "answer": "\n".join(lines), "observed_at": day.date().isoformat(),
            "stale": False, "source": "European Central Bank (via Frankfurter)"}


async def answer(req: dict) -> dict:
    if req["kind"] == "crypto":
        return await crypto_answer(req["coin"], req["currencies"])
    return await fx_answer(req["base"], req["quote"], req.get("amount"))
