# providers/yahoo.py — Yahoo! Finance (unofficial chart endpoint, no key)
#
# Yahoo! closed its official Finance API in 2017; this uses the same
# undocumented endpoint as yfinance and similar tools, which can change
# or be rate-limited without notice.
#
# SPDX-License-Identifier: GPL-3.0-or-later

import math
import urllib.parse
from gettext import gettext as _

from .base import NotSupported, Provider, Quote, QuoteError, RateLimited

CHART_URL = "https://query1.finance.yahoo.com/v8/finance/chart/{symbol}"

RANGES = {
    "1d": ("1d", "5m"),
    "1mo": ("1mo", "1d"),
    "6mo": ("6mo", "1d"),
    "1y": ("1y", "1d"),
    "5y": ("5y", "1wk"),
}

# Currencies Yahoo reports in minor units
MINOR_UNITS = {"GBp": ("GBP", 100.0), "GBX": ("GBP", 100.0),
               "ZAc": ("ZAR", 100.0), "ILA": ("ILS", 100.0)}


def _number(value):
    if isinstance(value, (int, float)) and math.isfinite(value):
        return float(value)
    return None


def parse_chart(payload, range_id="1d"):
    """Turn a Yahoo chart JSON document into a Quote."""
    chart = (payload or {}).get("chart") or {}
    error = chart.get("error")
    if error:
        raise QuoteError(error.get("description") or error.get("code") or _("Unknown error"))
    results = chart.get("result") or []
    if not results:
        raise QuoteError(_("No data for this symbol"))
    result = results[0]
    meta = result.get("meta") or {}

    price = _number(meta.get("regularMarketPrice"))
    if price is None:
        raise QuoteError(_("No price available for this symbol"))

    previous = _number(meta.get("previousClose"))
    if previous is None and range_id == "1d":
        # For a one-day chart, chartPreviousClose is yesterday's close
        previous = _number(meta.get("chartPreviousClose"))

    timestamps = result.get("timestamp") or []
    quote_lists = (result.get("indicators") or {}).get("quote") or [{}]
    closes = (quote_lists[0] or {}).get("close") or []
    points = [(int(t), float(c)) for t, c in zip(timestamps, closes)
              if c is not None and _number(c) is not None]

    currency = meta.get("currency") or ""
    if currency in MINOR_UNITS:
        currency, factor = MINOR_UNITS[currency]
        price /= factor
        previous = previous / factor if previous is not None else None
        points = [(t, c / factor) for t, c in points]

    symbol = meta.get("symbol") or ""
    return Quote(
        symbol=symbol,
        name=meta.get("longName") or meta.get("shortName") or symbol,
        currency=currency,
        price=price,
        previous_close=previous,
        exchange_code=meta.get("exchangeName") or "",
        exchange_name=meta.get("fullExchangeName") or meta.get("exchangeName") or "",
        market_time=meta.get("regularMarketTime"),
        points=points,
        source="yahoo",
    )


class YahooProvider(Provider):
    id = "yahoo"
    name = "Yahoo! Finance"
    website = "https://finance.yahoo.com"
    markets = frozenset({"NYSE", "STO", "OSL"})
    supports_history = True
    supports_fx = True
    delay_minutes = 15
    description = _("No key needed. Covers all three exchanges, price history and "
                    "exchange rates. Unofficial: Yahoo! can change or limit it at any time.")

    def chart(self, symbol, range_id):
        if range_id not in RANGES:
            raise NotSupported(range_id)
        yahoo_range, interval = RANGES[range_id]
        url = CHART_URL.format(symbol=urllib.parse.quote(symbol, safe=""))
        status, payload = self.http_json(url, {"range": yahoo_range, "interval": interval,
                                               "includePrePost": "false"})
        if status in (401, 403):
            raise RateLimited(_("Yahoo! Finance refused the request ({code})").format(
                code=status))
        return parse_chart(payload, range_id)

    def quote(self, instrument):
        return self.chart(instrument.symbol, "1d")

    def lookup(self, symbol):
        return self.chart(symbol, "1d")

    def history(self, instrument, range_id):
        return self.chart(instrument.symbol, range_id)

    def fx_rate(self, from_currency, to_currency):
        return self.chart(f"{from_currency}{to_currency}=X", "1d").price
