"""
Django views for yoro-maps — tile serving and routing API.
"""

from __future__ import annotations

import sqlite3

from django.conf import settings
from django.http import HttpResponse, JsonResponse
from django.views.decorators.http import require_GET

from yoromaps.routing import route as do_route
from yoromaps.routing import route_from_codes
from yoromaps.tiles import get_tile


def _get_maps_db() -> str:
    """Get the path to the maps database from Django settings."""
    return settings.DATABASES.get("maps", {}).get("NAME", "")


@require_GET
def tile_view(request, z, x, y):
    """Serve a map tile from the .yoromaps database.

    ``GET /maps/tiles/{z}/{x}/{y}.png``
    """
    db_path = _get_maps_db()
    if not db_path:
        return HttpResponse(status=404)

    conn = sqlite3.connect(db_path)
    conn.row_factory = sqlite3.Row
    data = get_tile(conn, int(z), int(x), int(y))
    conn.close()

    if data:
        resp = HttpResponse(data, content_type="image/png")
        resp["Cache-Control"] = "public, max-age=86400"
        return resp
    return HttpResponse(status=404)


@require_GET
def route_view(request):
    """Calculate a route between Yoro codes.

    ``GET /maps/route/?codes=ML-ABC,ML-XYZ``
    """
    import yoro

    codes_str = request.GET.get("codes", "")
    codes = [c.strip() for c in codes_str.split(",") if c.strip()]

    if len(codes) < 2:
        return JsonResponse({"error": "At least 2 Yoro codes required"}, status=400)

    db_path = _get_maps_db()
    if not db_path:
        return JsonResponse({"error": "Maps database not configured"}, status=500)

    conn = sqlite3.connect(db_path)
    conn.row_factory = sqlite3.Row

    try:
        legs = route_from_codes(conn, codes)
    except ValueError as e:
        conn.close()
        return JsonResponse({"error": str(e)}, status=400)

    conn.close()

    total_km = sum(leg.distance_km for leg in legs)
    total_min = sum(leg.duration_min for leg in legs)

    return JsonResponse({
        "total_distance_km": total_km,
        "total_duration_min": total_min,
        "legs": [
            {
                "distance_km": leg.distance_km,
                "duration_min": leg.duration_min,
                "found": leg.found,
                "geometry": leg.geometry,
                "steps": leg.steps,
            }
            for leg in legs
        ],
    })
