"""api.v1.billing — Usage and billing query endpoints."""
from __future__ import annotations
from fastapi import APIRouter, Depends, Query
from agentpaas.api.deps import get_tenant, get_database
from agentpaas.api.middleware.auth import TenantContext
from agentpaas.db.models import Database

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

@router.get("/usage")
async def get_usage(
    group_by: str = Query("agent", description="Group by: agent, model, day"),
    tenant: TenantContext = Depends(get_tenant),
    db: Database = Depends(get_database),
):
    if group_by == "agent":
        rows = db.fetchall(
            "SELECT agent_id, COUNT(*) as runs, SUM(input_tokens) as input_tokens, "
            "SUM(output_tokens) as output_tokens, SUM(duration_ms) as total_ms "
            "FROM runs WHERE tenant_id = ? AND status = 'completed' GROUP BY agent_id",
            (tenant.tenant_id,))
    else:
        rows = db.fetchall(
            "SELECT COUNT(*) as runs, SUM(input_tokens) as input_tokens, "
            "SUM(output_tokens) as output_tokens FROM runs WHERE tenant_id = ?",
            (tenant.tenant_id,))
    return {"usage": rows, "tenant_id": tenant.tenant_id}
