"""Cost tracking API — usage, budgets, and spending dashboard."""

from __future__ import annotations

from fastapi import APIRouter, Request
from pydantic import BaseModel

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


class BudgetUpdate(BaseModel):
    daily: float | None = None
    monthly: float | None = None
    enforce: bool | None = None


@router.get("")
async def get_usage(request: Request, days: int = 7) -> dict:
    """Get usage summary for the last N days."""
    tracker = request.app.state.cost_tracker
    return await tracker.get_usage_summary(days=days)


@router.get("/budget")
async def check_budget(request: Request) -> dict:
    """Check current budget status."""
    tracker = request.app.state.cost_tracker
    return await tracker.check_budget()


@router.put("/budget")
async def update_budget(request: Request, body: BudgetUpdate) -> dict:
    """Update daily/monthly budget limits."""
    tracker = request.app.state.cost_tracker
    tracker.set_budgets(daily=body.daily, monthly=body.monthly)
    if body.enforce is not None:
        tracker._enforce_budget = body.enforce

    # Persist to settings
    request.app.state.settings_service.update_section("costs", {
        "daily_budget": tracker._daily_budget,
        "monthly_budget": tracker._monthly_budget,
        "enforce_budget": tracker._enforce_budget,
    })

    return await tracker.check_budget()


@router.get("/today")
async def today_cost(request: Request) -> dict:
    """Get today's spending."""
    tracker = request.app.state.cost_tracker
    return {"cost": await tracker.get_daily_cost()}


@router.get("/bill/daily")
async def daily_bill(request: Request, date: str | None = None) -> dict:
    """Get itemized daily bill — cost breakdown by action and model.

    Shows every LLM call made on a given day with model, tokens, cost.
    Grouped by action type (chat, compile, briefing, etc.) and by model.
    """
    tracker = request.app.state.cost_tracker
    return await tracker.get_daily_bill(date=date)


@router.get("/bill/monthly")
async def monthly_bill(request: Request, month: str | None = None) -> dict:
    """Get monthly bill — daily totals + model and action breakdown.

    Shows cost per day, totals by model, totals by action type, budget status.
    """
    tracker = request.app.state.cost_tracker
    return await tracker.get_monthly_bill(month=month)
