"""Market Intelligence API Endpoints."""
from __future__ import annotations

from typing import Any

from fastapi import APIRouter, Query

from backend.app.config.settings import settings
from backend.app.market_data.feed_manager import feed_manager

router = APIRouter(prefix="/market", tags=["Market Data"])


@router.get("/symbols")
async def get_allowed_symbols() -> list[str]:
    """List allowed liquid trading symbols."""
    return settings.ALLOWED_SYMBOLS


@router.get("/ticker")
async def get_ticker(symbol: str = Query("BTCUSDT")) -> dict[str, Any]:
    """Fetch current ticker price and volume."""
    t = feed_manager.fetch_ticker(symbol)
    return {
        "symbol": t.symbol,
        "last_price": float(t.last_price),
        "bid_price": float(t.bid_price),
        "ask_price": float(t.ask_price),
        "volume_24h": float(t.volume_24h),
        "price_24h_pcnt": float(t.price_24h_pcnt),
        "high_24h": float(t.high_24h),
        "low_24h": float(t.low_24h),
        "timestamp": t.timestamp,
    }


@router.get("/klines")
async def get_klines(
    symbol: str = Query("BTCUSDT"),
    interval: str = Query("15m"),
    limit: int = Query(150, ge=10, le=500),
) -> list[dict[str, Any]]:
    """Fetch historical candlesticks."""
    candles = feed_manager.fetch_klines(symbol, interval, limit)
    return [
        {
            "timestamp": c.timestamp,
            "open": float(c.open),
            "high": float(c.high),
            "low": float(c.low),
            "close": float(c.close),
            "volume": float(c.volume),
        }
        for c in candles
    ]


@router.get("/orderbook")
async def get_orderbook(
    symbol: str = Query("BTCUSDT"),
    limit: int = Query(25, ge=5, le=50),
) -> dict[str, Any]:
    """Fetch orderbook depth and spread."""
    ob = feed_manager.fetch_orderbook(symbol, limit)
    return {
        "symbol": ob.symbol,
        "spread": float(ob.spread),
        "mid_price": float(ob.mid_price),
        "bids": [{"price": float(b.price), "size": float(b.size)} for b in ob.bids[:limit]],
        "asks": [{"price": float(a.price), "size": float(a.size)} for a in ob.asks[:limit]],
        "timestamp": ob.timestamp,
    }
