"""API routes for Dashboard statistics."""

from fastapi import APIRouter, Depends

from tracker.db.session import get_connection

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


def _db():
    conn = get_connection()
    try:
        yield conn
    finally:
        conn.close()


@router.get("")
def get_stats(conn=Depends(_db)):
    """Dashboard-level KPI statistics."""
    vorlagen_total = conn.execute("SELECT COUNT(*) as c FROM vorlagen").fetchone()["c"]
    beratungen_total = conn.execute("SELECT COUNT(*) as c FROM beratungen").fetchone()["c"]
    ketten_total = conn.execute("SELECT COUNT(*) as c FROM ketten").fetchone()["c"]

    # Vorlagen by type
    typ_rows = conn.execute("""
        SELECT typ, COUNT(*) as c FROM vorlagen
        WHERE typ IS NOT NULL
        GROUP BY typ ORDER BY c DESC
    """).fetchall()

    # Ketten by status
    status_rows = conn.execute("""
        SELECT status, COUNT(*) as c FROM ketten
        WHERE status IS NOT NULL
        GROUP BY status ORDER BY c DESC
    """).fetchall()

    # Ketten by type
    ketten_typ_rows = conn.execute("""
        SELECT typ, COUNT(*) as c FROM ketten
        WHERE typ IS NOT NULL
        GROUP BY typ ORDER BY c DESC
    """).fetchall()

    # Recent activity (last 10 Vorlagen)
    recent = conn.execute("""
        SELECT id, aktenzeichen, betreff, typ, datum_eingang
        FROM vorlagen
        WHERE datum_eingang IS NOT NULL
        ORDER BY datum_eingang DESC
        LIMIT 10
    """).fetchall()

    # Parteien with antrag counts
    parteien = conn.execute("""
        SELECT p.kuerzel, p.name, p.farbe, COUNT(a.vorlage_id) as anzahl
        FROM parteien p
        LEFT JOIN antragsteller a ON p.id = a.partei_id
        GROUP BY p.id
        ORDER BY anzahl DESC
    """).fetchall()

    # Gremien with beratung counts
    gremien = conn.execute("""
        SELECT g.name, g.kuerzel, g.typ, COUNT(b.id) as anzahl
        FROM gremien g
        LEFT JOIN beratungen b ON g.id = b.gremium_id
        GROUP BY g.id
        ORDER BY anzahl DESC
        LIMIT 15
    """).fetchall()

    # Zeitliche Verteilung (Vorlagen pro Monat, letzte 24 Monate)
    timeline = conn.execute("""
        SELECT strftime('%Y-%m', datum_eingang) as monat, COUNT(*) as c
        FROM vorlagen
        WHERE datum_eingang IS NOT NULL
        GROUP BY monat
        ORDER BY monat DESC
        LIMIT 24
    """).fetchall()

    return {
        "vorlagen_total": vorlagen_total,
        "beratungen_total": beratungen_total,
        "ketten_total": ketten_total,
        "vorlagen_nach_typ": [{"typ": r["typ"], "anzahl": r["c"]} for r in typ_rows],
        "ketten_nach_status": [{"status": r["status"], "anzahl": r["c"]} for r in status_rows],
        "ketten_nach_typ": [{"typ": r["typ"], "anzahl": r["c"]} for r in ketten_typ_rows],
        "letzte_vorlagen": [
            {
                "id": r["id"],
                "aktenzeichen": r["aktenzeichen"],
                "betreff": r["betreff"],
                "typ": r["typ"],
                "datum_eingang": r["datum_eingang"],
            }
            for r in recent
        ],
        "parteien": [
            {"kuerzel": r["kuerzel"], "name": r["name"], "farbe": r["farbe"], "anzahl": r["anzahl"]}
            for r in parteien
        ],
        "gremien": [
            {"name": r["name"], "kuerzel": r["kuerzel"], "typ": r["typ"], "anzahl": r["anzahl"]}
            for r in gremien
        ],
        "timeline": [{"monat": r["monat"], "anzahl": r["c"]} for r in reversed(timeline)],
    }


@router.get("/ketten-stats")
def get_ketten_stats(conn=Depends(_db)):
    """Aggregated Ketten status distribution with breakdowns."""
    # Status by type
    rows = conn.execute("""
        SELECT k.typ, k.status, COUNT(*) as c
        FROM ketten k
        GROUP BY k.typ, k.status
        ORDER BY k.typ, c DESC
    """).fetchall()

    by_type: dict = {}
    for r in rows:
        typ = r["typ"] or "unbekannt"
        if typ not in by_type:
            by_type[typ] = []
        by_type[typ].append({"status": r["status"], "anzahl": r["c"]})

    # Status counts with average age
    status_detail = conn.execute("""
        SELECT status,
               COUNT(*) as anzahl,
               AVG(julianday('now') - julianday(status_seit)) as avg_tage,
               AVG(vertagungen_count) as avg_vertagungen
        FROM ketten
        WHERE status IS NOT NULL
        GROUP BY status
        ORDER BY anzahl DESC
    """).fetchall()

    # Versandungs-Fruhwarnung: beschlossen > 6 Monate ohne Bericht
    fruehwarnung = conn.execute("""
        SELECT COUNT(*) as c FROM ketten
        WHERE status = 'beschlossen'
          AND julianday('now') - julianday(status_seit) > 180
    """).fetchone()["c"]

    return {
        "nach_typ": by_type,
        "status_detail": [
            {
                "status": r["status"],
                "anzahl": r["anzahl"],
                "avg_tage": round(r["avg_tage"] or 0, 1),
                "avg_vertagungen": round(r["avg_vertagungen"] or 0, 1),
            }
            for r in status_detail
        ],
        "versandungs_fruehwarnung": fruehwarnung,
    }
