import dataclasses
from typing import Annotated

from fastapi import HTTPException, Request
from fastapi.params import Form
from fastapi.responses import HTMLResponse
from folkugat_web.api.router import get_router
from folkugat_web.fragments.tema import lyrics as lyrics_fragments
from folkugat_web.services import auth
from folkugat_web.services.temes import lyrics as lyrics_service

router = get_router()


@router.get("/api/tema/{tema_id}/lyric/{lyric_id}")
def lyric(
    request: Request,
    logged_in: auth.LoggedIn,
    tema_id: int,
    lyric_id: int,
):
    lyric = lyrics_service.get_lyric_by_id(lyric_id=lyric_id, tema_id=tema_id)
    if not lyric:
        raise HTTPException(status_code=404, detail="Could not find lyric!")
    return lyrics_fragments.lyric(request=request, logged_in=logged_in, lyric=lyric)


@router.put("/api/tema/{tema_id}/lyric/{lyric_id}")
def set_lyric(
    request: Request,
    logged_in: auth.RequireLogin,
    tema_id: int,
    lyric_id: int,
    title: Annotated[str, Form()],
    content: Annotated[str, Form()],
    max_columns: Annotated[str | None, Form()] = None,
):
    lyric = lyrics_service.get_lyric_by_id(lyric_id=lyric_id, tema_id=tema_id)
    if not lyric:
        raise HTTPException(status_code=404, detail="Could not find lyric!")
    
    # Parse max_columns from string to int if provided
    max_columns_int = None
    if max_columns is not None and max_columns.strip():
        try:
            max_columns_int = int(max_columns.strip())
        except ValueError:
            raise HTTPException(status_code=400, detail="max_columns must be a valid integer")
    
    try:
        new_lyric = lyrics_service.update_lyric(lyric=lyric, title=title, content=content, max_columns=max_columns_int)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    
    return lyrics_fragments.lyric(request=request, logged_in=logged_in, lyric=new_lyric)


@router.post("/api/tema/{tema_id}/lyric")
def add_lyric(
    request: Request,
    logged_in: auth.RequireLogin,
    tema_id: int,
):
    lyric = lyrics_service.create_lyric(tema_id=tema_id)
    return lyrics_fragments.lyric_editor(
        request=request,
        logged_in=logged_in,
        lyric=lyric,
    )


@router.delete("/api/tema/{tema_id}/lyric/{lyric_id}")
def delete_lyric(
    tema_id: int,
    lyric_id: int,
):
    lyrics_service.delete_lyric(lyric_id=lyric_id, tema_id=tema_id)
    return HTMLResponse()


@router.get("/api/tema/{tema_id}/editor/lyric/{lyric_id}")
def lyric_editor(
    request: Request,
    logged_in: auth.RequireLogin,
    tema_id: int,
    lyric_id: int,
):
    lyric = lyrics_service.get_lyric_by_id(lyric_id=lyric_id, tema_id=tema_id)
    if not lyric:
        raise HTTPException(status_code=404, detail="Could not find lyric!")
    return lyrics_fragments.lyric_editor(
        request=request,
        logged_in=logged_in,
        lyric=lyric,
    )
