"""Stats and cost endpoints."""

from __future__ import annotations

from datetime import UTC, datetime
from typing import Any

from aiohttp import web

from dobby.models import TaskStatus


async def stats(request: web.Request) -> web.Response:
    store = request.app["store"]
    all_tasks = await store.list_tasks()
    all_results = await store.list_results()
    summary: dict[str, Any] = {s.value: 0 for s in TaskStatus}
    for task in all_tasks:
        summary[task.status.value] += 1
    summary["total_cost_usd"] = sum(
        (result.cost or {}).get("cost_usd", 0.0)
        for result in all_results
    )
    summary["input_tokens"] = sum(
        (result.cost or {}).get("input_tokens", 0)
        for result in all_results
    )
    summary["output_tokens"] = sum(
        (result.cost or {}).get("output_tokens", 0)
        for result in all_results
    )
    summary["total_tokens"] = sum(
        (result.cost or {}).get("total_tokens", 0)
        for result in all_results
    )
    return web.json_response(summary)


async def stats_cost(request: web.Request) -> web.Response:
    """Cost breakdown by project and time range."""
    from datetime import timedelta

    store = request.app["store"]
    all_tasks = await store.list_tasks()
    all_results = await store.list_results()

    now = datetime.now(UTC)
    today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
    week_start = today_start - timedelta(days=today_start.weekday())

    # Build task_id -> project mapping
    task_project = {t.id: t.project for t in all_tasks}

    # Per-project cost, cost today, cost this week
    by_project: dict[str, dict[str, Any]] = {}
    cost_today = 0.0
    cost_week = 0.0
    cost_total = 0.0
    tokens_today = 0
    tokens_week = 0
    tokens_total = 0

    for r in all_results:
        cost = (r.cost or {}).get("cost_usd", 0.0)
        tokens = (r.cost or {}).get("total_tokens", 0)
        input_tokens = (r.cost or {}).get("input_tokens", 0)
        output_tokens = (r.cost or {}).get("output_tokens", 0)
        project = task_project.get(r.task_id, "unknown")
        completed_at = r.completed_at

        cost_total += cost
        tokens_total += tokens

        # Parse completion time for time-range bucketing
        is_today = False
        is_week = False
        if completed_at:
            try:
                ct = datetime.fromisoformat(completed_at.replace("Z", "+00:00"))
                if ct >= today_start:
                    is_today = True
                if ct >= week_start:
                    is_week = True
            except (ValueError, TypeError):
                pass

        if is_today:
            cost_today += cost
            tokens_today += tokens
        if is_week:
            cost_week += cost
            tokens_week += tokens

        entry = by_project.setdefault(project, {
            "cost_usd": 0.0, "input_tokens": 0, "output_tokens": 0,
            "total_tokens": 0, "task_count": 0,
            "cost_today": 0.0, "cost_week": 0.0,
        })
        entry["cost_usd"] += cost
        entry["input_tokens"] += input_tokens
        entry["output_tokens"] += output_tokens
        entry["total_tokens"] += tokens
        entry["task_count"] += 1
        if is_today:
            entry["cost_today"] += cost
        if is_week:
            entry["cost_week"] += cost

    return web.json_response({
        "cost_total": cost_total,
        "cost_today": cost_today,
        "cost_week": cost_week,
        "tokens_total": tokens_total,
        "tokens_today": tokens_today,
        "tokens_week": tokens_week,
        "by_project": by_project,
    })
