"""BAN YARO — Widget-Snapshot Endpoint"""

import json, random
from fastapi import APIRouter, Depends
from database import db
from auth import get_current_user

router = APIRouter()


@router.get("/snapshot")
async def widget_snapshot(user=Depends(get_current_user)):
    """Liefert kompakte Widget-Daten: Hund, nächste Erinnerung, zufälliges Tagebuchbild."""
    with db() as conn:
        # Aktiver Hund (erster oder letzter genutzter)
        dog = conn.execute(
            "SELECT id, name, rasse, foto_url FROM dogs WHERE user_id=? ORDER BY id LIMIT 1",
            (user["id"],)
        ).fetchone()

        if not dog:
            return {"dog": None}

        dog_id = dog["id"]

        # Nächste fällige Erinnerung
        reminder = conn.execute(
            """SELECT bezeichnung, naechstes, typ FROM health
               WHERE dog_id=? AND naechstes IS NOT NULL AND naechstes >= date('now')
               ORDER BY naechstes ASC LIMIT 1""",
            (dog_id,)
        ).fetchone()

        # Zufälliges Tagebuchbild (letzte 50 Einträge mit Bild)
        photos = conn.execute(
            """SELECT media_url, titel, datum FROM diary
               WHERE dog_id=? AND media_url IS NOT NULL
               ORDER BY datum DESC LIMIT 50""",
            (dog_id,)
        ).fetchall()

        random_photo = dict(random.choice(photos)) if photos else None

        # Anzahl überfälliger Erinnerungen
        overdue = conn.execute(
            """SELECT COUNT(*) as n FROM health
               WHERE dog_id=? AND naechstes IS NOT NULL AND naechstes < date('now')""",
            (dog_id,)
        ).fetchone()["n"]

    return {
        "dog":          dict(dog),
        "reminder":     dict(reminder) if reminder else None,
        "random_photo": random_photo,
        "overdue":      overdue,
    }
