"""BAN YARO — Fortschritts-Lober"""
from fastapi import APIRouter, Depends, Query
from auth import get_current_user
from database import db
from datetime import date

router = APIRouter()

def _current_week_key():
    d = date.today()
    return f"{d.isocalendar()[0]}-W{d.isocalendar()[1]:02d}"

@router.get("/current")
async def get_current_praise(dog_id: int = Query(...), user=Depends(get_current_user)):
    """Gibt den Lob-Text der aktuellen Woche zurück."""
    week_key = _current_week_key()
    with db() as conn:
        # Sicherheitscheck: Hund gehört dem User?
        dog = conn.execute(
            """SELECT d.id, d.name FROM dogs d
               LEFT JOIN dog_shares ds ON ds.dog_id=d.id AND ds.shared_with_id=?
               WHERE d.id=? AND (d.user_id=? OR ds.id IS NOT NULL)""",
            (user["id"], dog_id, user["id"])
        ).fetchone()
        if not dog:
            return {"praise": None}

        row = conn.execute(
            "SELECT praise_text, generated_at FROM weekly_praise WHERE dog_id=? AND week_key=?",
            (dog_id, week_key)
        ).fetchone()

    if not row:
        return {"praise": None, "week_key": week_key}
    return {"praise": row["praise_text"], "week_key": week_key, "generated_at": row["generated_at"]}
