from __future__ import annotations

from fastapi import APIRouter, Depends
from fastapi import Query

from app.db import database
from app.v1.dependencies.auth import get_current_userdetails
from app.v1.services.alerts import get_top_signals_service


router = APIRouter()


@router.get("/alerts", summary="Alerts & Signals (Top Signals only, DB-only)")
async def get_alerts_top_signals(
    limit: int = Query(10, ge=1, le=50, description="Max top signals to return"),
    db=Depends(database.get_mongo_db),
    current_user=Depends(get_current_userdetails),
):
    """Return Top Signals only.

    IMPORTANT:
    - DB-only (no Zerodha, no GPT)
    - Universe:
      - Normal user: portfolio only
      - Super admin (role==1): portfolio + ET movers

    Response shape matches existing Alerts page expectations.
    """

    top = get_top_signals_service(db, current_user=current_user, limit=limit)

    # Keep backward-compatible structure for the existing Alerts UI tabs.
    return {
        "status": "ok",
        "source": top.get("source"),
        "counts": {
            "top_signals": (top.get("counts") or {}).get("top_signals", 0),
            "monitoring": 0,
            "triggered": 0,
            "closed": 0,
        },
        "data": {
            "top_signals": top.get("top_signals") or [],
            "monitoring": [],
            "triggered": [],
            "closed": [],
        },
    }


@router.get("/alerts/top-signals", summary="Top Signals only (DB-only)")
async def get_top_signals(
    limit: int = Query(10, ge=1, le=50, description="Max top signals to return"),
    db=Depends(database.get_mongo_db),
    current_user=Depends(get_current_userdetails),
):
    return get_top_signals_service(db, current_user=current_user, limit=limit)
