"""Cost monitoring API routes."""

import logging
from typing import Any

from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel

from ieum.server.auth import get_request_user_id

logger = logging.getLogger(__name__)

router = APIRouter()


def get_session_service(request: Request) -> Any:
    """Dependency to get the session service."""
    return request.app.state.session_service


class CostStatus(BaseModel):
    """Session cost status response."""

    model_name: str | None = None
    session_cost: float = 0.0
    pricing_available: bool = False
    input_price_per_1m: float | None = None
    output_price_per_1m: float | None = None


@router.get("/{session_id}/cost", response_model=CostStatus)
async def get_session_cost(
    session_id: str,
    request: Request,
    session_service: Any = Depends(get_session_service),
) -> CostStatus:
    """Get cost information for a session.

    Session cost is accumulated on the Session object by the WebSocket
    adapter after each agent execution completes.
    """
    user_id = get_request_user_id(request)
    session = session_service.get_session(session_id, user_id=user_id)
    if session is None:
        raise HTTPException(status_code=404, detail="Session not found")

    model_name = session.model_name

    # Look up pricing info
    pricing = None
    if model_name:
        from ieum.pricing import get_model_pricing
        pricing = get_model_pricing(model_name)

    return CostStatus(
        model_name=model_name,
        session_cost=session.session_cost,
        pricing_available=pricing is not None,
        input_price_per_1m=pricing["input"] if pricing else None,
        output_price_per_1m=pricing["output"] if pricing else None,
    )
