# providers/stooq.py — Stooq (experimental)
#
# Since March 2026 Stooq's CSV downloads need an API key, issued after a
# captcha at stooq.com/q/d/?s=spy.us&get_apikey. In June 2026 Stooq added
# a JavaScript bot check, so automated requests may be refused even with a
# key. Without a valid key Stooq answers 200 with a text page rather than
# CSV, which is detected here.
#
# SPDX-License-Identifier: GPL-3.0-or-later

import csv
import io
import time
from datetime import datetime, timezone
from gettext import gettext as _

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

CSV_URL = "https://stooq.com/q/d/l/"


def stooq_symbol(ticker):
    return ticker.lower() + ".us"


def parse_daily_csv(text):
    """[(unix_time, close)] from Stooq's Date,Open,High,Low,Close,Volume CSV."""
    stripped = text.lstrip()
    if not stripped.lower().startswith("date"):
        lowered = stripped.lower()
        if "apikey" in lowered or "captcha" in lowered or "<html" in lowered:
            raise RateLimited(_("Stooq refused the request (API key or bot check)"))
        if "no data" in lowered:
            raise QuoteError(_("Stooq does not know this symbol"))
        raise QuoteError(_("Unexpected response from {source}").format(source="Stooq"))
    reader = csv.DictReader(io.StringIO(stripped))
    fields = {f.lower(): f for f in reader.fieldnames or []}
    if "date" not in fields or "close" not in fields:
        raise QuoteError(_("Unexpected response from {source}").format(source="Stooq"))
    points = []
    for row in reader:
        try:
            day = datetime.strptime(row[fields["date"]], "%Y-%m-%d")
            close = float(row[fields["close"]])
        except (ValueError, KeyError, TypeError):
            continue
        points.append((int(day.replace(hour=21, tzinfo=timezone.utc).timestamp()), close))
    if not points:
        raise QuoteError(_("Stooq does not know this symbol"))
    return sorted(points)


class StooqProvider(Provider):
    id = "stooq"
    name = "Stooq"
    website = "https://stooq.com"
    key_url = "https://stooq.com/q/d/?s=spy.us&get_apikey"
    needs_key = True
    markets = frozenset({"NYSE"})
    supports_history = True
    supports_fx = True
    delay_minutes = 24 * 60     # daily bars
    min_quote_age = 60 * 60
    experimental = True
    description = _("Experimental. Free key issued after a captcha. Daily NYSE prices and "
                    "exchange rates. A 2026 bot check may block automated requests.")

    def _daily(self, stooq_sym, days):
        self._require_key()
        params = {"s": stooq_sym, "i": "d" if days <= 400 else "w", "apikey": self.api_key}
        if days:
            start = time.strftime("%Y%m%d", time.gmtime(time.time() - days * 86400))
            params["d1"] = start
            params["d2"] = time.strftime("%Y%m%d", time.gmtime())
        _status, text = self.http_get(CSV_URL, params, accept="text/csv")
        return parse_daily_csv(text)

    def quote(self, instrument):
        if not self.covers(instrument.exchange):
            raise NotSupported(_("Stooq is only used for NYSE stocks"))
        points = self._daily(stooq_symbol(instrument.ticker), 10)
        previous = points[-2][1] if len(points) > 1 else None
        return Quote(symbol=instrument.symbol, name=instrument.ticker, currency="USD",
                     price=points[-1][1], previous_close=previous,
                     market_time=points[-1][0], source=self.id,
                     delay_minutes=self.delay_minutes)

    def history(self, instrument, range_id):
        if range_id == "1d":
            raise NotSupported(_("Stooq has daily prices only"))
        days = {"1mo": 31, "6mo": 183, "1y": 366, "5y": 5 * 366}[range_id]
        points = self._daily(stooq_symbol(instrument.ticker), days)
        return Quote(symbol=instrument.symbol, name=instrument.ticker, currency="USD",
                     price=points[-1][1], previous_close=None, points=points, source=self.id)

    def fx_rate(self, from_currency, to_currency):
        points = self._daily(f"{from_currency}{to_currency}".lower(), 10)
        return points[-1][1]
