"""Historical data endpoints (quote-hist and hist)."""

from __future__ import annotations

from datetime import datetime
from typing import Any, Dict, List, Literal, Optional

from sd_api.client.base import BaseClient
from sd_api.models.quote import Quote, QuoteHistory
from sd_api.config import settings
from sd_api.logging import get_logger

logger = get_logger("client.history")


class HistoryMixin:
    """Endpoints under /api/quote-hist and /api/hist."""

    def __init__(self, base: BaseClient) -> None:
        self._base = base

    def quote_history(
        self,
        symbol: str,
        *,
        limit: int = 100,
        from_ts: int | None = None,
        to_ts: int | None = None,
    ) -> QuoteHistory:
        """GET /api/quote-hist — historical ticks from quote_ticks table.

        Parameters
        ----------
        symbol : str
            Product symbol (e.g. "XAUUSD").
        limit : int
            Maximum number of records (default: 100, max: 5000).
        from_ts : int, optional
            Start timestamp in ms epoch. Defaults to 1 hour ago.
        to_ts : int, optional
            End timestamp in ms epoch. Defaults to now + 1 min.

        Returns
        -------
        QuoteHistory
            List of Quote objects ordered chronologically.
        """
        symbol = symbol.upper().strip()
        params: Dict[str, Any] = {"symbol": symbol, "limit": min(limit, 5000)}
        if from_ts is not None:
            params["from"] = str(from_ts)
        if to_ts is not None:
            params["to"] = str(to_ts)
        data = self._base.get("/api/quote-hist", params=params)
        quotes = [Quote.from_api(item) for item in data.get("data", [])]
        return QuoteHistory(
            symbol=symbol,
            data=quotes,
            from_ts=data.get("from"),
            to_ts=data.get("to"),
        )

    def hist_raw(
        self,
        symbol: str,
        *,
        limit: int = 1000,
        from_ts: int | None = None,
        to_ts: int | None = None,
    ) -> List[Dict[str, Any]]:
        """GET /api/hist?agg=raw — raw tick data from tick_logs table.

        Returns raw rows as dicts (bid, ask, spread, mid, tick_time, received_at).
        """
        symbol = symbol.upper().strip()
        params: Dict[str, Any] = {"symbol": symbol, "agg": "raw", "limit": min(limit, 10000)}
        if from_ts is not None:
            params["from"] = str(from_ts)
        if to_ts is not None:
            params["to"] = str(to_ts)
        data = self._base.get("/api/hist", params=params)
        return data.get("data", [])

    def hist_agg(
        self,
        symbol: str,
        *,
        agg: Literal["1s", "5s", "1min"] = "1min",
        limit: int = 1000,
        from_ts: int | None = None,
        to_ts: int | None = None,
    ) -> List[Dict[str, Any]]:
        """GET /api/hist?agg={agg} — aggregated OHLC from tick_logs.

        Parameters
        ----------
        agg : str
            Aggregation interval: "1s", "5s", or "1min".
        """
        symbol = symbol.upper().strip()
        params: Dict[str, Any] = {"symbol": symbol, "agg": agg, "limit": min(limit, 10000)}
        if from_ts is not None:
            params["from"] = str(from_ts)
        if to_ts is not None:
            params["to"] = str(to_ts)
        data = self._base.get("/api/hist", params=params)
        return data.get("data", [])
