# quotes.py — fetching quotes through pluggable sources, with fallback and cache
#
# The service asks the primary source first and, if enabled, the other
# configured sources that cover the stock's market. When every source fails
# or is rate-limited, the last known value is kept (and marked stale) rather
# than dropped. Rate-limited sources cool down with exponential backoff.
#
# SPDX-License-Identifier: GPL-3.0-or-later

import threading
import time
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from datetime import datetime, timezone
from gettext import gettext as _

from .exchanges import display_symbol
from .providers import (DEFAULT_PROVIDER, PROVIDER_CLASSES, Instrument, NotSupported,
                        Quote, QuoteError, RateLimited, create_providers)

__all__ = ["Quote", "QuoteError", "QuoteService", "RefreshResult", "parse_chart"]

from .providers.yahoo import parse_chart  # noqa: E402  (kept for compatibility)

BACKOFF_START = 60
BACKOFF_MAX = 30 * 60


def _today():
    return datetime.now(timezone.utc).strftime("%Y-%m-%d")


@dataclass
class RefreshResult:
    updated: set = field(default_factory=set)      # symbols with a fresh price
    reused: set = field(default_factory=set)       # recent enough, not re-fetched
    stale: set = field(default_factory=set)        # showing a cached price
    missing: set = field(default_factory=set)      # no price at all
    errors: dict = field(default_factory=dict)     # symbol or pair -> message
    rate_limited: bool = False
    retry_at: float | None = None                  # when a limited source is usable again
    sources: set = field(default_factory=set)      # provider ids that answered

    @property
    def ok(self):
        return not self.stale and not self.missing and not self.errors


class QuoteService:
    """Fetches quotes off the main thread and hands results back via `dispatch`.

    `dispatch(callback, *args)` must run the callback on the UI thread
    (the application passes a GLib.idle_add wrapper).
    """

    def __init__(self, dispatch=None, providers=None, cache=None, clock=time.time,
                 max_workers=6):
        self._dispatch = dispatch or (lambda callback, *args: callback(*args))
        self._pool = ThreadPoolExecutor(max_workers=max_workers)
        self._lock = threading.Lock()
        self._clock = clock
        self.providers = providers or create_providers()
        self.primary = DEFAULT_PROVIDER
        self.use_fallbacks = True
        self.cache = cache
        self.quotes, self.rates, self.budgets = (cache.load() if cache else ({}, {}, {}))
        self.stale = set(self.quotes)          # nothing on disk is current yet
        self.cooldown = {}                     # provider id -> unix time usable again
        self.failures = {}                     # provider id -> consecutive rate limits
        self.last_success = max((q.fetched_at for q in self.quotes.values()), default=None)

    def shutdown(self):
        self._pool.shutdown(wait=False, cancel_futures=True)

    # ---- configuration ----------------------------------------------------

    def configure(self, primary=None, use_fallbacks=None, keys=None):
        if primary in self.providers:
            self.primary = primary
        if use_fallbacks is not None:
            self.use_fallbacks = use_fallbacks
        for pid, key in (keys or {}).items():
            if pid in self.providers:
                self.providers[pid].api_key = (key or "").strip()
                self.cooldown.pop(pid, None)

    @property
    def primary_provider(self):
        return self.providers[self.primary]

    def chain(self, exchange=None, need=None):
        """Providers to try, primary first. need: None, 'history' or 'fx'."""
        builtin = [c.id for c in PROVIDER_CLASSES]
        others = sorted(self.providers, key=lambda pid: (pid not in builtin,
                                                          builtin.index(pid) if pid in builtin
                                                          else 0, pid))
        order = [self.primary] + [pid for pid in others if pid != self.primary]
        if not self.use_fallbacks:
            order = order[:1]
        result = []
        for pid in order:
            p = self.providers[pid]
            if not p.configured:
                continue
            if exchange and not p.covers(exchange):
                continue
            if need == "history" and not p.supports_history:
                continue
            if need == "fx" and not p.supports_fx:
                continue
            result.append(p)
        return result

    # ---- calling providers -------------------------------------------------

    def _spend(self, provider):
        if not provider.daily_limit:
            return
        with self._lock:
            entry = self.budgets.get(provider.id)
            if not entry or entry.get("day") != _today():
                entry = self.budgets[provider.id] = {"day": _today(), "used": 0}
            if entry["used"] >= provider.daily_limit:
                raise RateLimited(_("{source}: daily limit of {n} requests used").format(
                    source=provider.name, n=provider.daily_limit), self._seconds_to_midnight())
            entry["used"] += 1

    def _seconds_to_midnight(self):
        now = datetime.now(timezone.utc)
        return int(86400 - (now.hour * 3600 + now.minute * 60 + now.second)) + 60

    def _call(self, provider, method, *args):
        now = self._clock()
        until = self.cooldown.get(provider.id, 0)
        if until > now:
            raise RateLimited(_("{source} is limiting requests").format(source=provider.name),
                              int(until - now))
        try:
            self._spend(provider)
            value = getattr(provider, method)(*args)
        except RateLimited as e:
            with self._lock:
                n = self.failures.get(provider.id, 0)
                self.failures[provider.id] = n + 1
                wait = e.retry_after or min(BACKOFF_START * 2 ** n, BACKOFF_MAX)
                self.cooldown[provider.id] = self._clock() + wait
            raise
        with self._lock:
            self.failures.pop(provider.id, None)
        return value

    def _try_chain(self, providers, method, *args):
        """Returns (value, provider). Raises the most useful error if all fail."""
        if not providers:
            raise NotSupported(_("No data source is set up for this market"))
        errors = []
        for p in providers:
            try:
                return self._call(p, method, *args), p
            except NotSupported as e:
                errors.append(e)
            except QuoteError as e:
                errors.append(e)
            except Exception as e:  # never let a worker die silently
                errors.append(QuoteError(str(e) or e.__class__.__name__))
        # Prefer a rate-limit or real failure over "not supported"
        for e in errors:
            if not isinstance(e, NotSupported):
                raise e
        raise errors[0]

    @staticmethod
    def instrument(symbol, exchange):
        return Instrument(symbol, display_symbol(symbol, exchange), exchange)

    def _submit(self, func, callback):
        def job():
            try:
                value, error = func(), None
            except QuoteError as e:
                value, error = None, str(e)
            except Exception as e:
                value, error = None, str(e) or e.__class__.__name__
            self._dispatch(callback, value, error)
        self._pool.submit(job)

    # ---- public operations -------------------------------------------------

    def lookup(self, symbol, exchange, callback):
        """Look a new symbol up. callback(quote | None, error | None)"""
        inst = self.instrument(symbol, exchange)

        def func():
            providers = self.chain(exchange)
            # Prefer a source that reports the listing exchange and company name
            if self.use_fallbacks:
                providers.sort(key=lambda p: p.id != "yahoo")
            quote, provider = self._try_chain(providers, "quote", inst)
            quote.symbol = quote.symbol or symbol
            quote.source = provider.id
            quote.fetched_at = self._clock()
            return quote
        self._submit(func, callback)

    def history(self, symbol, exchange, range_id, callback):
        """callback(quote_with_points | None, error | None)"""
        inst = self.instrument(symbol, exchange)

        def func():
            quote, _p = self._try_chain(self.chain(exchange, "history"), "history",
                                        inst, range_id)
            return quote
        self._submit(func, callback)

    def refresh(self, holdings, base_currency, callback, force=False):
        """holdings: [(symbol, exchange, currency)]. callback(RefreshResult) on UI thread."""
        holdings = list(dict.fromkeys(holdings))

        def job():
            result = RefreshResult()
            fresh = {}
            now = self._clock()

            def fetch(symbol, exchange):
                cached = self.quotes.get(symbol)
                if (not force and cached and symbol not in self.stale and cached.source
                        and cached.source in self.providers):
                    age = now - cached.fetched_at
                    if age < self.providers[cached.source].min_quote_age:
                        return "reused", cached
                quote, provider = self._try_chain(self.chain(exchange), "quote",
                                                  self.instrument(symbol, exchange))
                old = self.quotes.get(symbol)
                # Fallback sources know less: keep name/points from what we had
                if old and provider.id != "yahoo":
                    if quote.name == display_symbol(symbol, exchange):
                        quote.name = old.name
                    quote.exchange_code = quote.exchange_code or old.exchange_code
                    quote.exchange_name = quote.exchange_name or old.exchange_name
                quote.symbol, quote.source, quote.fetched_at = symbol, provider.id, self._clock()
                quote.delay_minutes = provider.delay_minutes
                return "updated", quote

            futures = {s: self._pool.submit(fetch, s, ex) for s, ex, _c in holdings}
            for symbol, future in futures.items():
                try:
                    kind, quote = future.result()
                except RateLimited as e:
                    result.rate_limited = True
                    result.errors[symbol] = str(e)
                    kind, quote = None, None
                except Exception as e:
                    result.errors[symbol] = str(e) or e.__class__.__name__
                    kind, quote = None, None
                if kind == "updated":
                    fresh[symbol] = quote
                    result.updated.add(symbol)
                    result.sources.add(quote.source)
                elif kind == "reused":
                    result.reused.add(symbol)
                    result.sources.add(quote.source)
                elif symbol in self.quotes:
                    result.stale.add(symbol)
                else:
                    result.missing.add(symbol)

            # Exchange rates for every currency we hold
            currencies = {q.currency for q in fresh.values() if q.currency}
            currencies |= {self.quotes[s].currency for s, _e, _c in holdings
                           if s in self.quotes and self.quotes[s].currency}
            currencies |= {c for _s, _e, c in holdings if c}
            fresh_rates = {}
            for c in sorted(currencies - {base_currency}):
                pair = c + base_currency
                cached = self.rates.get(pair)
                try:
                    rate, provider = self._try_chain(self.chain(need="fx"), "fx_rate",
                                                     c, base_currency)
                    fresh_rates[pair] = (rate, self._clock(), provider.id)
                except RateLimited as e:
                    result.rate_limited = True
                    result.errors[pair] = str(e)
                except Exception as e:
                    result.errors[pair] = str(e) or e.__class__.__name__
                if pair not in fresh_rates and not cached:
                    # A holding in this currency cannot be valued at all
                    for s, _e, hc in holdings:
                        q = fresh.get(s) or self.quotes.get(s)
                        if (q.currency if q else hc) == c:
                            result.missing.add(s)

            if result.rate_limited:
                waits = [t for pid, t in self.cooldown.items() if t > self._clock()]
                result.retry_at = min(waits) if waits else None
            self._dispatch(self._finish_refresh, fresh, fresh_rates, result, callback)

        threading.Thread(target=job, name="portfolio-refresh", daemon=True).start()

    def _finish_refresh(self, fresh, fresh_rates, result, callback):
        self.quotes.update(fresh)
        self.rates.update(fresh_rates)
        self.stale -= result.updated | result.reused
        self.stale |= result.stale
        if result.updated:
            self.last_success = self._clock()
        if self.cache:
            self.cache.save(self.quotes, self.rates, self.budgets)
        callback(result)

    # ---- reading -----------------------------------------------------------

    def rate(self, currency, base_currency):
        if not currency:
            return None
        if currency == base_currency:
            return 1.0
        entry = self.rates.get(currency + base_currency)
        if entry:
            return entry[0]
        inverse = self.rates.get(base_currency + currency)
        if inverse and inverse[0]:
            return 1.0 / inverse[0]
        return None

    def rate_info(self, currency, base_currency):
        """(rate, fetched_at, source) or None"""
        return self.rates.get(currency + base_currency)

    def is_stale(self, symbol):
        return symbol in self.stale

    def budget_used(self, provider_id):
        entry = self.budgets.get(provider_id)
        return entry["used"] if entry and entry.get("day") == _today() else 0

    def remember(self, quote):
        """Store a quote obtained from a lookup."""
        self.quotes[quote.symbol] = quote
        self.stale.discard(quote.symbol)
