"""BAN YARO — Hunde-Knigge Routes"""

from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel
from typing import Optional
from database import db
from auth import get_current_user, get_current_user_optional

router = APIRouter()


# ------------------------------------------------------------------
# Schemas
# ------------------------------------------------------------------
class VoteRequest(BaseModel):
    szenario_id: str
    answer: str


class KiRatRequest(BaseModel):
    situation: str


# ------------------------------------------------------------------
# POST /api/knigge/vote — Stimme abgeben oder ändern (Auth required)
# ------------------------------------------------------------------
@router.post("/vote")
async def vote(data: VoteRequest, user=Depends(get_current_user)):
    if not data.szenario_id or not data.answer:
        raise HTTPException(400, "szenario_id und answer sind erforderlich.")

    with db() as conn:
        # Upsert: vorhandene Stimme ersetzen oder neu anlegen
        conn.execute(
            """INSERT INTO knigge_votes (szenario_id, user_id, answer)
               VALUES (?, ?, ?)
               ON CONFLICT(szenario_id, user_id) DO UPDATE SET answer=excluded.answer""",
            (data.szenario_id, user["id"], data.answer),
        )
        rows = conn.execute(
            """SELECT answer, COUNT(*) as cnt
               FROM knigge_votes
               WHERE szenario_id=?
               GROUP BY answer""",
            (data.szenario_id,),
        ).fetchall()

    counts = {r["answer"]: r["cnt"] for r in rows}
    return {"counts": counts, "user_answer": data.answer}


# ------------------------------------------------------------------
# GET /api/knigge/votes?szenario_id= — Stimmen abrufen (kein Auth nötig)
# ------------------------------------------------------------------
@router.get("/votes")
async def get_votes(
    szenario_id: str = Query(...),
    user=Depends(get_current_user_optional),
):
    with db() as conn:
        rows = conn.execute(
            """SELECT answer, COUNT(*) as cnt
               FROM knigge_votes
               WHERE szenario_id=?
               GROUP BY answer""",
            (szenario_id,),
        ).fetchall()
        user_answer = None
        if user:
            row = conn.execute(
                "SELECT answer FROM knigge_votes WHERE szenario_id=? AND user_id=?",
                (szenario_id, user["id"]),
            ).fetchone()
            if row:
                user_answer = row["answer"]

    counts = {r["answer"]: r["cnt"] for r in rows}
    return {"counts": counts, "user_answer": user_answer}


# ------------------------------------------------------------------
# POST /api/knigge/ki-rat — KI-Situationsberater (Auth required)
# ------------------------------------------------------------------
@router.post("/ki-rat")
async def ki_rat(data: KiRatRequest, user=Depends(get_current_user)):
    from ki import complete, KIUnavailableError, KIPremiumRequired

    if not data.situation or not data.situation.strip():
        raise HTTPException(400, "Situation darf nicht leer sein.")

    system = (
        "Du bist ein erfahrener Hundeexperte und Hundetrainer. "
        "Deine Aufgabe ist es, Hundebesitzern kurze, praktische Ratschläge zu geben. "
        "Antworte immer auf Deutsch, freundlich und verständlich."
    )
    prompt = (
        f"Situation: {data.situation.strip()}\n\n"
        "Gib einen kurzen, praktischen Rat (maximal 3 Sätze) was der Hundebesitzer tun sollte."
    )

    try:
        rat = await complete(
            prompt,
            system=system,
            max_tokens=300,
            requires_premium=False,
            user_is_premium=bool(user.get("is_premium")),
            user_id=user["id"],
        )
        return {"rat": rat}
    except KIPremiumRequired as e:
        raise HTTPException(402, str(e))
    except KIUnavailableError as e:
        raise HTTPException(503, str(e))
