# providers/base.py — interface every market data source implements
#
# SPDX-License-Identifier: GPL-3.0-or-later

import json
import time
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass, field
from gettext import gettext as _

USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) GNOME-Portfolio/0.2"
TIMEOUT = 15

# Chart ranges the UI offers
RANGE_IDS = ("1d", "1mo", "6mo", "1y", "5y")
RANGE_DAYS = {"1d": 1, "1mo": 31, "6mo": 183, "1y": 366, "5y": 5 * 366}


class QuoteError(Exception):
    """A request failed; the message is shown to the user."""


class RateLimited(QuoteError):
    """The source refused because of rate limits or a used-up daily quota."""

    def __init__(self, message, retry_after=None):
        super().__init__(message)
        self.retry_after = retry_after      # seconds, if the source said


class NotSupported(QuoteError):
    """The source does not cover this market, range or feature."""


@dataclass
class Quote:
    symbol: str                  # canonical (Yahoo-style) symbol, e.g. "EQNR.OL"
    name: str
    currency: str
    price: float
    previous_close: float | None
    exchange_code: str = ""
    exchange_name: str = ""
    market_time: int | None = None          # time of the last trade (unix)
    points: list = field(default_factory=list)   # [(unix_time, close), ...]
    fetched_at: float = field(default_factory=time.time)
    source: str = ""                        # provider id
    delay_minutes: int = 15

    @property
    def change(self):
        if self.previous_close is None:
            return None
        return self.price - self.previous_close

    @property
    def change_percent(self):
        if not self.previous_close:
            return None
        return (self.price - self.previous_close) / self.previous_close * 100.0

    def to_dict(self):
        d = dict(self.__dict__)
        d["points"] = [list(p) for p in self.points]
        return d

    @classmethod
    def from_dict(cls, d):
        known = {k: d[k] for k in cls.__dataclass_fields__ if k in d}
        known["points"] = [tuple(p) for p in known.get("points", [])]
        return cls(**known)


@dataclass(frozen=True)
class Instrument:
    """What a provider needs to know to look a stock up."""
    symbol: str          # canonical Yahoo-style symbol ("VOLV-B.ST")
    ticker: str          # bare ticker ("VOLV-B")
    exchange: str        # "NYSE", "STO" or "OSL"


class Provider:
    """Base class for market data sources.

    Subclasses set the class attributes and implement quote(); history()
    and fx_rate() are optional (raise NotSupported).
    """

    id = ""
    name = ""
    website = ""
    key_url = ""               # where to get an API key, if one is needed
    needs_key = False
    markets = frozenset()      # exchange ids this source is known to cover
    supports_history = False
    supports_fx = False
    delay_minutes = 15
    daily_limit = None         # requests/day on the free plan, if any
    min_quote_age = 0          # seconds a quote is reused before asking again
    experimental = False
    description = ""

    def __init__(self, api_key=""):
        self.api_key = (api_key or "").strip()

    # ---- capability checks --------------------------------------------

    @property
    def configured(self):
        return bool(self.api_key) or not self.needs_key

    def covers(self, exchange_id):
        return exchange_id in self.markets

    # ---- operations ----------------------------------------------------

    def quote(self, instrument):
        raise NotImplementedError

    def history(self, instrument, range_id):
        raise NotSupported(_("{source} has no price history").format(source=self.name))

    def fx_rate(self, from_currency, to_currency):
        raise NotSupported(_("{source} has no exchange rates").format(source=self.name))

    # ---- helpers -------------------------------------------------------

    def _require_key(self):
        if not self.api_key:
            raise NotSupported(_("{source} needs an API key").format(source=self.name))

    def http_get(self, url, params=None, accept="application/json"):
        if params:
            url = url + ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
        request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT,
                                                       "Accept": accept})
        try:
            with urllib.request.urlopen(request, timeout=TIMEOUT) as response:
                return response.status, response.read().decode("utf-8", "replace")
        except urllib.error.HTTPError as e:
            if e.code == 429:
                retry = e.headers.get("Retry-After") if e.headers else None
                raise RateLimited(_("{source} is limiting requests").format(source=self.name),
                                  int(retry) if retry and retry.isdigit() else None) from e
            if e.code in (401, 403):
                body = ""
                try:
                    body = e.read().decode("utf-8", "replace")
                except Exception:
                    pass
                return e.code, body
            try:
                return e.code, e.read().decode("utf-8", "replace")
            except Exception:
                raise QuoteError(_("{source}: server error ({code})").format(
                    source=self.name, code=e.code)) from e
        except (urllib.error.URLError, TimeoutError, OSError) as e:
            raise QuoteError(_("Could not reach {source}").format(source=self.name)) from e

    def http_json(self, url, params=None):
        status, body = self.http_get(url, params)
        try:
            return status, json.loads(body)
        except ValueError as e:
            raise QuoteError(_("Unexpected response from {source}").format(
                source=self.name)) from e
