# providers/finnhub.py — Finnhub (free API key)
#
# The free plan serves real-time quotes for US stocks (60 calls/minute).
# International markets and price candles require paid subscriptions.
#
# SPDX-License-Identifier: GPL-3.0-or-later

from gettext import gettext as _

from .base import NotSupported, Provider, Quote, QuoteError

API_URL = "https://finnhub.io/api/v1/quote"


def finnhub_symbol(ticker):
    # Finnhub writes US share classes with a dot: BRK.B
    return ticker.replace("-", ".")


def parse_quote(status, payload, instrument):
    if status in (401, 403):
        message = (payload or {}).get("error", "") if isinstance(payload, dict) else ""
        if "access" in message.lower():
            raise NotSupported(_("This needs a paid Finnhub plan"))
        raise QuoteError(_("Finnhub rejected the API key"))
    if not isinstance(payload, dict) or "c" not in payload:
        raise QuoteError(_("Unexpected response from {source}").format(source="Finnhub"))
    price = payload.get("c")
    # Unknown symbols come back as all zeros
    if not price and not payload.get("pc"):
        raise QuoteError(_("Finnhub does not know this symbol"))
    return Quote(
        symbol=instrument.symbol,
        name=instrument.ticker,
        currency="USD",
        price=float(price),
        previous_close=float(payload["pc"]) if payload.get("pc") else None,
        market_time=int(payload["t"]) if payload.get("t") else None,
        source="finnhub",
        delay_minutes=0,
    )


class FinnhubProvider(Provider):
    id = "finnhub"
    name = "Finnhub"
    website = "https://finnhub.io"
    key_url = "https://finnhub.io/register"
    needs_key = True
    markets = frozenset({"NYSE"})
    delay_minutes = 0
    description = _("Free key, 60 requests per minute. Real-time NYSE quotes only; "
                    "history and Nordic markets need a paid plan.")

    def quote(self, instrument):
        self._require_key()
        if not self.covers(instrument.exchange):
            raise NotSupported(_("Finnhub's free plan covers US stocks only"))
        status, payload = self.http_json(API_URL, {"symbol": finnhub_symbol(instrument.ticker),
                                                   "token": self.api_key})
        return parse_quote(status, payload, instrument)
