"""API routes for Orte und Karten-Daten."""

from fastapi import APIRouter, Depends

from tracker.db.session import get_connection

router = APIRouter(prefix="/orte", tags=["Orte"])


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


@router.get("")
def list_orte(conn=Depends(_db)):
    """Alle geocodierten Orte mit Vorlagen-Anzahl."""
    rows = conn.execute("""
        SELECT o.id, o.name, o.typ, o.lat, o.lon, o.vorlage_count
        FROM orte o
        WHERE o.lat IS NOT NULL
        ORDER BY o.vorlage_count DESC
    """).fetchall()
    
    return [
        {
            "id": r[0],
            "name": r[1],
            "typ": r[2],
            "lat": r[3],
            "lon": r[4],
            "vorlage_count": r[5]
        }
        for r in rows
    ]


@router.get("/geojson")
def get_orte_geojson(conn=Depends(_db)):
    """Orte als GeoJSON für Leaflet."""
    rows = conn.execute("""
        SELECT o.id, o.name, o.lat, o.lon, o.vorlage_count,
               GROUP_CONCAT(v.aktenzeichen, ', ') as vorlagen
        FROM orte o
        LEFT JOIN vorlagen_orte vo ON o.id = vo.ort_id
        LEFT JOIN vorlagen v ON vo.vorlage_id = v.id
        WHERE o.lat IS NOT NULL
        GROUP BY o.id
        ORDER BY o.vorlage_count DESC
    """).fetchall()
    
    features = []
    for r in rows:
        features.append({
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [r[3], r[2]]  # lon, lat
            },
            "properties": {
                "id": r[0],
                "name": r[1],
                "vorlage_count": r[4],
                "vorlagen": r[5]
            }
        })
    
    return {
        "type": "FeatureCollection",
        "features": features
    }


@router.get("/{ort_id}/vorlagen")
def get_vorlagen_fuer_ort(ort_id: int, conn=Depends(_db)):
    """Alle Vorlagen die einen bestimmten Ort betreffen."""
    rows = conn.execute("""
        SELECT v.id, v.aktenzeichen, v.typ, v.betreff, v.datum_eingang, vo.kontext
        FROM vorlagen_orte vo
        JOIN vorlagen v ON vo.vorlage_id = v.id
        WHERE vo.ort_id = ?
        ORDER BY v.datum_eingang DESC
    """, (ort_id,)).fetchall()
    
    return [
        {
            "id": r[0],
            "aktenzeichen": r[1],
            "typ": r[2],
            "betreff": r[3],
            "datum_eingang": r[4],
            "kontext": r[5]
        }
        for r in rows
    ]
