"""Therminal CLI — quick lookups from the terminal.

Install: pip install therminal-py[cli]
Usage:   therminal health
         therminal candles KXHIGHNY-26MAR20-T50 --from 2026-03-01
         therminal observations NYC --units metric --limit 5
         therminal climate NYC --from 2026-03-15 --to 2026-03-20
"""

from __future__ import annotations

import json
import sys

try:
    import typer
    from rich.console import Console
    from rich.table import Table
except ImportError:
    print("CLI requires extra dependencies. Install with: pip install therminal-py[cli]")
    sys.exit(1)

from therminal.client import TherminalClient
from therminal.config import DEFAULT_BASE_URL

app = typer.Typer(help="Therminal — Kalshi temperature markets + NWS weather data")
console = Console()


def _print_json(data):
    """Pretty-print JSON data."""
    console.print_json(json.dumps(data, default=str))


def _print_table(data: list[dict], columns: list[str] | None = None):
    """Print a list of dicts as a rich table."""
    if not data:
        console.print("[dim]No results[/dim]")
        return
    cols = columns or list(data[0].keys())
    table = Table()
    for c in cols:
        table.add_column(c)
    for row in data:
        table.add_row(*[str(row.get(c, "")) for c in cols])
    console.print(table)


@app.command()
def health(base_url: str = typer.Option(DEFAULT_BASE_URL, help="API base URL")):
    """Check API health status."""
    with TherminalClient(base_url=base_url) as client:
        _print_json(client.health())


@app.command()
def series(
    ticker: str = typer.Argument(None, help="Series ticker (omit for list)"),
    active: bool = typer.Option(False, help="Only active series"),
    limit: int = typer.Option(20, help="Max results"),
    base_url: str = typer.Option(DEFAULT_BASE_URL),
):
    """List series or get series detail."""
    with TherminalClient(base_url=base_url) as client:
        if ticker:
            _print_json(client.series_detail(ticker))
        else:
            _print_table(
                client.series(active=active, limit=limit),
                columns=["ticker", "measure_type", "station_code", "active", "title"],
            )


@app.command()
def candles(
    market: str = typer.Argument(..., help="Market ticker"),
    from_date: str = typer.Option(None, "--from", help="Start date (YYYY-MM-DD or RFC3339)"),
    to_date: str = typer.Option(None, "--to", help="End date"),
    interval: int = typer.Option(None, help="Candle interval (1, 5, 15, 30, 60, 1440)"),
    no_fill: bool = typer.Option(False, help="Disable forward-fill"),
    aggregate: int = typer.Option(None, help="Aggregate interval (minutes)"),
    tz: str = typer.Option(None, help="Timezone"),
    limit: int = typer.Option(20, help="Max results"),
    output_json: bool = typer.Option(False, "--json", help="Output as JSON"),
    base_url: str = typer.Option(DEFAULT_BASE_URL),
):
    """Get OHLCV candles for a market."""
    with TherminalClient(base_url=base_url) as client:
        data = client.candles(
            market=market, from_date=from_date, to_date=to_date,
            interval=interval, fill=not no_fill, aggregate=aggregate,
            tz=tz, limit=limit,
        )
        if output_json:
            _print_json(data)
        else:
            _print_table(
                data,
                columns=["end_period_ts", "open", "high", "low", "close", "volume", "filled"],
            )


@app.command()
def observations(
    station: str = typer.Argument(..., help="Station code (e.g., NYC)"),
    from_date: str = typer.Option(None, "--from", help="Start date (RFC3339)"),
    to_date: str = typer.Option(None, "--to", help="End date"),
    units: str = typer.Option(None, help="Unit system (raw, metric, imperial)"),
    tz: str = typer.Option(None, help="Timezone"),
    limit: int = typer.Option(10, help="Max results"),
    output_json: bool = typer.Option(False, "--json", help="Output as JSON"),
    base_url: str = typer.Option(DEFAULT_BASE_URL),
):
    """Get weather observations for a station."""
    with TherminalClient(base_url=base_url) as client:
        data = client.observations(
            station=station, from_date=from_date, to_date=to_date,
            units=units, tz=tz, limit=limit,
        )
        if output_json:
            _print_json(data)
        else:
            _print_table(
                data,
                columns=["observed_at", "temp_f", "dewpoint_f", "wind_speed_kt",
                         "visibility_miles", "observation_type"],
            )


@app.command()
def climate(
    station: str = typer.Argument(..., help="Station code (e.g., NYC)"),
    from_date: str = typer.Option(None, "--from", help="Start date (YYYY-MM-DD)"),
    to_date: str = typer.Option(None, "--to", help="End date"),
    units: str = typer.Option(None, help="Unit system (raw, metric, imperial)"),
    limit: int = typer.Option(10, help="Max results"),
    base_url: str = typer.Option(DEFAULT_BASE_URL),
):
    """Get daily climate reports for a station."""
    with TherminalClient(base_url=base_url) as client:
        data = client.climate(
            station=station, from_date=from_date, to_date=to_date,
            units=units, limit=limit,
        )
        _print_table(
            data,
            columns=["observation_date", "high_temp_f", "low_temp_f", "report_type", "source"],
        )


@app.command()
def lob(
    market: str = typer.Argument(..., help="Market or series ticker"),
    is_series: bool = typer.Option(False, "--series", help="Treat argument as series ticker"),
    source: str = typer.Option("kalshi", help="Data source (kalshi, polymarket)"),
    date: str = typer.Option(None, help="Date (YYYY-MM-DD)"),
    from_date: str = typer.Option(None, "--from", help="Start date"),
    to_date: str = typer.Option(None, "--to", help="End date"),
    interval: int = typer.Option(60, help="Snapshot interval in seconds (1-3600)"),
    levels: int = typer.Option(10, help="Book depth per side (1-50)"),
    hour: int = typer.Option(None, help="Filter to single hour (0-23)"),
    limit: int = typer.Option(20, help="Max results to display"),
    output_json: bool = typer.Option(False, "--json", help="Output as JSON"),
    base_url: str = typer.Option(DEFAULT_BASE_URL),
):
    """Get limit order book snapshots for a market."""
    with TherminalClient(base_url=base_url) as client:
        kwargs: dict = {
            "source": source,
            "date": date,
            "from_date": from_date,
            "to_date": to_date,
            "interval": interval,
            "levels": levels,
            "hour": hour,
        }
        if is_series:
            kwargs["series"] = market
        else:
            kwargs["market"] = market

        data = client.lob(**kwargs)
        if output_json:
            _print_json(data)
        else:
            # Truncate for display
            display_data = data[:limit] if len(data) > limit else data
            _print_table(
                display_data,
                columns=["ts", "market_id", "best_bid", "best_ask", "spread", "mid"],
            )
            if len(data) > limit:
                console.print(f"[dim]... {len(data) - limit} more rows[/dim]")


if __name__ == "__main__":
    app()
