from typing import Optional

from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session

from auth import get_current_user
from database import get_db
from models import User
from schemas import (
    MemoryTransformerPredictResponse,
    MemoryVisualizationResponse,
    WordCreate,
    WordMemoryDetailResponse,
    WordOut,
    WordUpdate,
)
from services.memory_transformer import memory_transformer_service
from services.memory_visual_service import memory_visual_service
from services.word_service import word_service

router = APIRouter(prefix="/api/words", tags=["words"])


@router.post("", response_model=WordOut)
def create_word(
    data: WordCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    word = word_service.create_word(db, current_user, data.model_dump())
    return word


@router.get("", response_model=list[WordOut])
def list_words(
    status: Optional[str] = None,
    book_id: Optional[int] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    return word_service.list_words(db, current_user, status, book_id=book_id)


@router.get("/memory-viz", response_model=MemoryVisualizationResponse)
def memory_visualization(
    book_id: int = 0,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    return memory_visual_service.get_visualization(db, current_user, book_id=book_id)


@router.get("/{word_id}/memory", response_model=WordMemoryDetailResponse)
def word_memory(
    word_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    return memory_visual_service.get_word_memory(db, current_user, word_id)


@router.get("/{word_id}/memory-model", response_model=MemoryTransformerPredictResponse)
def word_memory_model(
    word_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    word = word_service.get_word(db, current_user, word_id)
    return memory_transformer_service.predict_for_word(db, current_user, word)


@router.get("/{word_id}", response_model=WordOut)
def get_word(
    word_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    return word_service.get_word(db, current_user, word_id)


@router.delete("/{word_id}")
def delete_word(
    word_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    word_service.delete_word(db, current_user, word_id)
    return {"ok": True}


@router.patch("/{word_id}", response_model=WordOut)
def update_word(
    word_id: int,
    data: WordUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    return word_service.update_word(db, current_user, word_id, data.model_dump(exclude_unset=True))
