"""Aggregate dashboard stats — 24h article counts, success rate, enablement."""
from __future__ import annotations

from datetime import datetime, timedelta
from typing import Any

from fastapi import Depends
from sqlalchemy import and_, case, func, select
from sqlalchemy.orm import Session

from govcrawler.models import Article, CrawlLog, CrawlSite, CrawlTarget

from ._common import _session, router


@router.get("/api/stats")
def stats(s: Session = Depends(_session)) -> dict[str, Any]:
    now = datetime.utcnow()
    last_24h = now - timedelta(hours=24)

    total_articles = s.execute(select(func.count(Article.id))).scalar_one() or 0
    ready_articles = (
        s.execute(select(func.count(Article.id)).where(Article.status == "ready")).scalar_one()
        or 0
    )
    unexported = (
        s.execute(
            select(func.count(Article.id)).where(
                and_(Article.status == "ready", Article.exported_to_rag_at.is_(None))
            )
        ).scalar_one()
        or 0
    )
    articles_24h = (
        s.execute(
            select(func.count(Article.id)).where(
                and_(Article.status == "ready", Article.fetched_at >= last_24h)
            )
        ).scalar_one()
        or 0
    )

    # 24h success rate via crawl_logs
    total_logs = (
        s.execute(
            select(func.count(CrawlLog.id)).where(CrawlLog.occurred_at >= last_24h)
        ).scalar_one()
        or 0
    )
    ok_logs = (
        s.execute(
            select(
                func.sum(case((CrawlLog.success.is_(True), 1), else_=0))
            ).where(CrawlLog.occurred_at >= last_24h)
        ).scalar_one()
        or 0
    )
    success_rate = (float(ok_logs) / total_logs) if total_logs else None

    # Site/target counts — useful admin cues
    site_total = s.execute(select(func.count(CrawlSite.id))).scalar_one() or 0
    site_enabled = (
        s.execute(select(func.count(CrawlSite.id)).where(CrawlSite.enabled.is_(True))).scalar_one()
        or 0
    )
    target_total = s.execute(select(func.count(CrawlTarget.id))).scalar_one() or 0
    target_enabled = (
        s.execute(
            select(func.count(CrawlTarget.id)).where(CrawlTarget.enabled.is_(True))
        ).scalar_one()
        or 0
    )

    return {
        "total_articles": int(total_articles),
        "ready_articles": int(ready_articles),
        "unexported_to_rag": int(unexported),
        "articles_24h": int(articles_24h),
        "fetch_attempts_24h": int(total_logs),
        "success_rate_24h": success_rate,
        "sites": {"total": int(site_total), "enabled": int(site_enabled)},
        "targets": {"total": int(target_total), "enabled": int(target_enabled)},
        "now": now.isoformat(),
    }
