from __future__ import annotations

import hmac
import logging
from typing import Literal

from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel, Field

from config.settings import settings
from execution.queue_handler import signal_queue
from price.cache import price_cache
from websocket.manager import ws_manager

logger = logging.getLogger(__name__)
router = APIRouter()

_startup_time: float | None = None  # يُضبَط من main.py


# ─── نماذج البيانات ────────────────────────────────────────────────────────────

class SignalRequest(BaseModel):
    token: str
    symbol: str
    action: Literal["BUY", "SELL"]
    quantity: float = Field(gt=0, description="الكمية يجب أن تكون أكبر من صفر")


class SignalResponse(BaseModel):
    status: str
    symbol: str
    action: str
    quantity: float
    cached_price: float | None
    queue_depth: int


class PriceResponse(BaseModel):
    symbol: str
    price: float
    stale: bool = False


# ─── نقاط النهاية ────────────────────────────────────────────────────────────

@router.post("/signal", response_model=SignalResponse, status_code=202)
async def receive_signal(request: SignalRequest) -> SignalResponse:
    # التحقق من الرمز السري (مقاومة هجمات التوقيت)
    if not hmac.compare_digest(request.token, settings.SIGNAL_TOKEN):
        logger.warning(f"رمز غير صحيح في طلب /signal")
        raise HTTPException(status_code=401, detail="رمز غير صالح")

    symbol = request.symbol.upper()
    if symbol not in settings.SYMBOLS:
        raise HTTPException(
            status_code=400,
            detail=f"الرمز {symbol} غير مدعوم. الرموز المتاحة: {settings.SYMBOLS}",
        )

    signal = {"symbol": symbol, "action": request.action, "quantity": request.quantity}
    await signal_queue.enqueue(signal)

    logger.info(f"إشارة مستلمة: {request.action} {request.quantity} {symbol}")

    return SignalResponse(
        status="queued",
        symbol=symbol,
        action=request.action,
        quantity=request.quantity,
        cached_price=price_cache.get(symbol),
        queue_depth=signal_queue.queue_depth,
    )


@router.get("/price", response_model=PriceResponse)
async def get_price(symbol: str = Query(..., description="مثال: BTCUSDT")) -> PriceResponse:
    symbol = symbol.upper()
    if symbol not in settings.SYMBOLS:
        raise HTTPException(
            status_code=400,
            detail=f"الرمز {symbol} غير مدعوم. الرموز المتاحة: {settings.SYMBOLS}",
        )

    price = price_cache.get(symbol)
    if price is None:
        raise HTTPException(
            status_code=404,
            detail=f"السعر غير متوفر بعد لـ {symbol}. انتظر بضع ثوانٍ.",
        )

    return PriceResponse(
        symbol=symbol,
        price=price,
        stale=price_cache.is_stale(symbol),
    )


@router.get("/health")
async def health() -> dict:
    import time as _time

    uptime = int(_time.time() - _startup_time) if _startup_time else 0
    return {
        "status": "ok",
        "mode": settings.TRADING_MODE,
        "symbols": settings.SYMBOLS,
        "ws_connections": ws_manager.connection_count,
        "queue_depth": signal_queue.queue_depth,
        "uptime_seconds": uptime,
    }
