"""Therminal API client — convenience facade composing WeatherHistory + MarketsClient.

For domain-specific usage, import directly:
    from therminal.weather import WeatherHistory, WeatherLive
    from therminal.markets import MarketsClient
"""

from __future__ import annotations

from pathlib import Path
from typing import Any

from therminal._http import HttpSession
from therminal.config import DEFAULT_BASE_URL, DEFAULT_TIMEOUT, TherminalConfig
from therminal.markets.client import MarketsClient
from therminal.weather.client import WeatherHistory


class TherminalClient:
    """Convenience facade composing WeatherHistory + MarketsClient.

    Provides the same method signatures as v0.5.0 for backward compatibility.
    For new code, prefer using WeatherHistory or MarketsClient directly.

    Args:
        base_url: API base URL. Defaults to https://api.mostlyright.xyz
        timeout: Request timeout in seconds. Defaults to 30.
        config: SDK configuration. Overrides base_url/timeout if provided.
    """

    def __init__(
        self,
        base_url: str = DEFAULT_BASE_URL,
        timeout: float = DEFAULT_TIMEOUT,
        config: TherminalConfig | None = None,
    ) -> None:
        self._config = config or TherminalConfig(base_url=base_url, timeout=timeout)
        self._http = HttpSession(self._config)
        self._weather = WeatherHistory(config=self._config, _session=self._http)
        self._markets = MarketsClient(config=self._config, _session=self._http)

    def close(self) -> None:
        """Close the underlying HTTP client."""
        self._http.close()

    def __enter__(self) -> TherminalClient:
        return self

    def __exit__(self, *args: Any) -> None:
        self.close()

    # ── Health ───────────────────────────────────────────────

    def health(self) -> dict[str, Any]:
        """Check API health status."""
        return self._http.get("/health")

    # ── Weather delegates ────────────────────────────────────

    def observations(
        self,
        station: str | None = None,
        from_date: str | None = None,
        to_date: str | None = None,
        obs_type: str | None = None,
        resolution: str | None = None,
        units: str | None = None,
        tz: str | None = None,
        format: str | None = None,
        columns: list[str] | None = None,
        limit: int = 1000,
        offset: int = 0,
        as_dataframe: bool = False,
        save_path: str | Path | None = None,
    ) -> Any:
        """Get weather observations. Delegates to WeatherHistory."""
        return self._weather.observations(
            station=station, from_date=from_date, to_date=to_date,
            obs_type=obs_type, resolution=resolution, units=units, tz=tz,
            format=format, columns=columns, limit=limit, offset=offset,
            as_dataframe=as_dataframe, save_path=save_path,
        )

    def climate(
        self,
        station: str | None = None,
        from_date: str | None = None,
        to_date: str | None = None,
        units: str | None = None,
        format: str | None = None,
        columns: list[str] | None = None,
        limit: int = 1000,
        offset: int = 0,
        as_dataframe: bool = False,
        save_path: str | Path | None = None,
    ) -> Any:
        """Get daily climate reports. Delegates to WeatherHistory."""
        return self._weather.climate(
            station=station, from_date=from_date, to_date=to_date,
            units=units, format=format, columns=columns, limit=limit,
            offset=offset, as_dataframe=as_dataframe, save_path=save_path,
        )

    def climate_gaps(
        self,
        station: str | None = None,
        from_date: str | None = None,
        to_date: str | None = None,
        as_dataframe: bool = False,
    ) -> Any:
        """Find gaps in climate history. Delegates to WeatherHistory."""
        return self._weather.climate_gaps(
            station=station, from_date=from_date, to_date=to_date,
            as_dataframe=as_dataframe,
        )

    # ── Markets delegates ────────────────────────────────────

    def series(
        self,
        active: bool | None = None,
        limit: int = 100,
        offset: int = 0,
        as_dataframe: bool = False,
    ) -> Any:
        """List event series. Delegates to MarketsClient."""
        return self._markets.series(
            active=active, limit=limit, offset=offset, as_dataframe=as_dataframe,
        )

    def series_detail(self, ticker: str) -> Any:
        """Get a single series. Delegates to MarketsClient."""
        return self._markets.series_detail(ticker)

    def markets(
        self,
        series: str | None = None,
        station: str | None = None,
        from_date: str | None = None,
        to_date: str | None = None,
        limit: int = 1000,
        offset: int = 0,
        as_dataframe: bool = False,
    ) -> Any:
        """List markets. Delegates to MarketsClient."""
        return self._markets.markets(
            series=series, station=station, from_date=from_date, to_date=to_date,
            limit=limit, offset=offset, as_dataframe=as_dataframe,
        )

    def market(self, ticker: str) -> Any:
        """Get a single market. Delegates to MarketsClient."""
        return self._markets.market(ticker)

    def candles(
        self,
        market: str | None = None,
        event: str | None = None,
        station: str | None = None,
        series: str | None = None,
        from_date: str | None = None,
        to_date: str | None = None,
        interval: int | None = None,
        fill: bool = True,
        aggregate: int | None = None,
        tz: str | None = None,
        format: str | None = None,
        columns: list[str] | None = None,
        limit: int = 10000,
        offset: int = 0,
        as_dataframe: bool = False,
        save_path: str | Path | None = None,
    ) -> Any:
        """Get OHLCV candles. Delegates to MarketsClient."""
        return self._markets.candles(
            market=market, event=event, station=station, series=series,
            from_date=from_date, to_date=to_date, interval=interval,
            fill=fill, aggregate=aggregate, tz=tz, format=format,
            columns=columns, limit=limit, offset=offset,
            as_dataframe=as_dataframe, save_path=save_path,
        )

    def lob(
        self,
        market: str | None = None,
        series: str | None = None,
        source: str = "kalshi",
        date: str | None = None,
        from_date: str | None = None,
        to_date: str | None = None,
        interval: int = 60,
        levels: int = 10,
        hour: int | None = None,
        format: str | None = None,
        columns: list[str] | None = None,
        as_dataframe: bool = False,
        save_path: str | Path | None = None,
    ) -> Any:
        """Get LOB snapshots. Delegates to MarketsClient."""
        return self._markets.lob(
            market=market, series=series, source=source, date=date,
            from_date=from_date, to_date=to_date, interval=interval,
            levels=levels, hour=hour, format=format, columns=columns,
            as_dataframe=as_dataframe, save_path=save_path,
        )
