"""Dashboard query helpers."""

from __future__ import annotations

from backend.db.connection import get_db


async def get_overview(days: int = 30) -> dict:
    """Get usage overview for the dashboard."""
    db = await get_db()

    total = await db.execute_fetchall(
        """SELECT
             COUNT(*) as total_requests,
             COALESCE(SUM(cost_usd), 0) as total_cost,
             COALESCE(SUM(tokens_in + tokens_out), 0) as total_tokens,
             COALESCE(AVG(latency_total_ms), 0) as avg_latency
           FROM usage_logs
           WHERE timestamp >= datetime('now', ?)""",
        (f"-{days} days",),
    )
    row = total[0] if total else {}

    return {
        "total_requests": row["total_requests"] if row else 0,
        "total_cost": round(row["total_cost"], 4) if row else 0,
        "total_tokens": row["total_tokens"] if row else 0,
        "avg_latency_ms": round(row["avg_latency"], 1) if row else 0,
    }


async def get_cost_by_model(days: int = 30) -> list[dict]:
    """Get cost breakdown by model."""
    db = await get_db()
    rows = await db.execute_fetchall(
        """SELECT model_id, COUNT(*) as requests, COALESCE(SUM(cost_usd), 0) as cost,
                  COALESCE(SUM(tokens_in), 0) as tokens_in, COALESCE(SUM(tokens_out), 0) as tokens_out
           FROM usage_logs WHERE timestamp >= datetime('now', ?)
           GROUP BY model_id ORDER BY cost DESC""",
        (f"-{days} days",),
    )
    return [dict(r) for r in rows]


async def get_cost_over_time(days: int = 30) -> list[dict]:
    """Get daily cost over time, split by model.
    
    Returns list of {date, model_id, cost, requests} rows.
    Frontend pivots this into multi-line chart data.
    """
    db = await get_db()
    rows = await db.execute_fetchall(
        """SELECT DATE(timestamp) as date, model_id, 
                  COALESCE(SUM(cost_usd), 0) as cost,
                  COUNT(*) as requests
           FROM usage_logs WHERE timestamp >= datetime('now', ?)
           GROUP BY DATE(timestamp), model_id ORDER BY date, model_id""",
        (f"-{days} days",),
    )
    return [dict(r) for r in rows]


async def get_recent_requests(limit: int = 50) -> list[dict]:
    """Get recent routing decisions."""
    db = await get_db()
    rows = await db.execute_fetchall(
        """SELECT timestamp, model_id, strategy, tokens_in, tokens_out,
                  cost_usd, latency_total_ms, was_fallback, fallback_from
           FROM usage_logs ORDER BY timestamp DESC LIMIT ?""",
        (limit,),
    )
    return [dict(r) for r in rows]


async def get_savings_estimate(days: int = 30) -> dict:
    """Estimate savings vs. always using the most expensive model."""
    db = await get_db()

    actual = await db.execute_fetchall(
        "SELECT COALESCE(SUM(cost_usd), 0) as cost FROM usage_logs WHERE timestamp >= datetime('now', ?)",
        (f"-{days} days",),
    )
    actual_cost = actual[0]["cost"] if actual else 0

    # Get the most expensive model used
    max_cost_row = await db.execute_fetchall(
        """SELECT model_id, 
                  COALESCE(SUM(cost_usd), 0) / NULLIF(COALESCE(SUM(tokens_in + tokens_out), 0), 0) * 1000 as cost_per_1k
           FROM usage_logs WHERE timestamp >= datetime('now', ?)
           GROUP BY model_id ORDER BY cost_per_1k DESC LIMIT 1""",
        (f"-{days} days",),
    )
    max_cost = max_cost_row[0]["cost_per_1k"] if max_cost_row and max_cost_row[0]["cost_per_1k"] else 0

    # Estimate: if all tokens went through the most expensive model
    token_row = await db.execute_fetchall(
        "SELECT COALESCE(SUM(tokens_in + tokens_out), 0) as total FROM usage_logs WHERE timestamp >= datetime('now', ?)",
        (f"-{days} days",),
    )
    total_tokens = token_row[0]["total"] if token_row else 0
    hypothetical_cost = (total_tokens / 1000) * max_cost

    return {
        "actual_cost": round(actual_cost, 4),
        "hypothetical_cost": round(hypothetical_cost, 4),
        "savings": round(max(0, hypothetical_cost - actual_cost), 4),
        "savings_pct": round((1 - actual_cost / hypothetical_cost) * 100, 1) if hypothetical_cost > 0 else 0,
    }
