"""billing.report — Usage report generation."""
from __future__ import annotations
from typing import Dict, List
from agentpaas.db.session import get_db


def monthly_report(tenant_id: str, period: str = "") -> Dict:
    db = get_db()
    where = f"tenant_id='{tenant_id}'"
    if period:
        where += f" AND created_at LIKE '{period}%'"
    rows = db.fetchall(
        f"SELECT agent_id, COUNT(*) as runs, "
        f"COALESCE(SUM(input_tokens),0) as input_tokens, "
        f"COALESCE(SUM(output_tokens),0) as output_tokens, "
        f"COALESCE(SUM(cost_usd),0) as cost_usd "
        f"FROM usage_records WHERE {where} GROUP BY agent_id")
    total_cost = sum(r["cost_usd"] for r in rows)
    total_tokens = sum(r["input_tokens"] + r["output_tokens"] for r in rows)
    return {"tenant_id": tenant_id, "period": period, "total_cost_usd": round(total_cost, 4),
            "total_tokens": total_tokens, "breakdown": rows}
