from __future__ import annotations

from fastapi import APIRouter, HTTPException, Query

from app.schemas.schemas import PositionMetrics
from app.services.ai_context_builder import ai_context_builder
from app.services.price_anchor import price_anchor_service

router = APIRouter(prefix="/positions", tags=["Positions"])


@router.get("/metrics", response_model=PositionMetrics)
async def get_position_metrics(
    symbol: str = Query("XAUUSD", description="Symbol, e.g., XAUUSD or BTCUSDT"),
    timeframe: str = Query("1m", description="Timeframe such as 1m,5m,1h"),
    limit: int = Query(400, ge=50, le=2000, description="Number of bars to analyze"),
) -> PositionMetrics:
    try:
        sym = symbol.upper().replace("/", "")
        ctx = ai_context_builder.build_request(sym, timeframe, limit)
        metrics = ai_context_builder.build_metrics(sym, timeframe, ctx.price_data)
        anchor_price = await price_anchor_service.get_anchor_price(sym)
        return price_anchor_service.apply_anchor(metrics, anchor_price)
    except ValueError as exc:
        raise HTTPException(status_code=404, detail=str(exc))
    except Exception as exc:
        raise HTTPException(status_code=500, detail=f"Failed to compute position metrics: {exc}")
