"""BAN YARO — Nearby Alerts (Giftköder + Vermisste Hunde)"""
import math
from datetime import datetime
from fastapi import APIRouter, Depends

from database import db
from auth import get_current_user_optional as get_optional_user

router = APIRouter()

_RADIUS_M = 20_000  # 20 km


def _haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
    R = 6_371_000
    p1, p2 = math.radians(lat1), math.radians(lat2)
    dp = math.radians(lat2 - lat1)
    dl = math.radians(lon2 - lon1)
    a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
    return 2 * R * math.asin(math.sqrt(a))


@router.get("")
async def nearby_alerts(lat: float, lon: float, user=Depends(get_optional_user)):
    now = datetime.utcnow().isoformat()
    with db() as conn:
        poisons = conn.execute(
            "SELECT lat, lon FROM poison WHERE geloest=0 AND expires_at > ?", (now,)
        ).fetchall()
        lost = conn.execute(
            "SELECT lat, lon FROM lost_dogs WHERE is_active=1"
        ).fetchall()
        # Letzten Standort des Users für geo-basierte Push-Filter speichern
        if user:
            conn.execute(
                """UPDATE push_subscriptions SET last_lat=?, last_lon=?
                   WHERE user_id=?""",
                (lat, lon, user["id"])
            )

    has_poison = any(_haversine(lat, lon, r["lat"], r["lon"]) <= _RADIUS_M for r in poisons)
    has_lost   = any(_haversine(lat, lon, r["lat"], r["lon"]) <= _RADIUS_M for r in lost)

    return {"poison": has_poison, "lost": has_lost}
