from typing import Annotated

from fastapi import HTTPException, Request, UploadFile
from fastapi.params import File, Form, Param
from fastapi.responses import HTMLResponse
from folkugat_web.api.router import get_router
from folkugat_web.fragments.tema import links as links_fragments
from folkugat_web.model import temes as model
from folkugat_web.services import auth
from folkugat_web.services import files as files_service
from folkugat_web.services.temes import links as links_service
from folkugat_web.services.temes import query as temes_q

router = get_router()


@router.get("/api/tema/{tema_id}/link/{link_id}")
def link(request: Request, logged_in: auth.LoggedIn, tema_id: int, link_id: int):
    link = links_service.get_link_by_id(link_id=link_id, tema_id=tema_id)
    if not link:
        raise HTTPException(status_code=404, detail="Could not find link!")
    return links_fragments.link(request=request, logged_in=logged_in, link=link)


@router.put("/api/tema/{tema_id}/link/{link_id}")
async def set_link(
    request: Request,
    logged_in: auth.RequireLogin,
    tema_id: int,
    link_id: int,
    content_type: Annotated[model.ContentType, Form()],
    title: Annotated[str | None, Form()] = None,
    url: Annotated[str | None, Form()] = None,
    upload_file: Annotated[UploadFile | None, File()] = None,
):
    if upload_file:
        url = await files_service.store_tema_file(tema_id=tema_id, upload_file=upload_file)

    link_type = links_service.guess_link_type(url or '')
    new_link = model.Link(
        id=link_id,
        tema_id=tema_id,
        content_type=content_type,
        link_type=link_type,
        url=(url or '').strip(),
        title=(title or '').strip(),
    )
    links_service.update_link(link=new_link)
    return links_fragments.link(request=request, logged_in=logged_in, link=new_link)


@router.post("/api/tema/{tema_id}/link")
def create_link(
    request: Request,
    logged_in: auth.RequireLogin,
    tema_id: int,
):
    link = links_service.create_link(tema_id=tema_id)
    return links_fragments.link_editor(
        request=request,
        logged_in=logged_in,
        link=link,
    )


@router.delete("/api/tema/{tema_id}/link/{link_id}")
def delete_link(
    _: auth.RequireLogin,
    tema_id: int,
    link_id: int,
):
    links_service.delete_link(link_id=link_id, tema_id=tema_id)
    files_service.clean_orphan_files()
    return HTMLResponse(
        headers={
            "HX-Trigger": f"reload-tema-{tema_id}-score"
        }
    )


@router.get("/api/tema/{tema_id}/link/{link_id}/icon")
def link_icon(
    request: Request,
    logged_in: auth.LoggedIn,
    tema_id: int,
    link_id: int,
    content_type: Annotated[model.ContentType, Param()],
    url: Annotated[str, Param()],
):
    link = model.Link(
        id=link_id,
        tema_id=tema_id,
        content_type=content_type,
        link_type=links_service.guess_link_type(url),
        url=url,
    )
    return links_fragments.link_icon(
        request=request,
        logged_in=logged_in,
        link=link,
    )


@router.get("/api/tema/{tema_id}/score")
def get_score(
    request: Request,
    logged_in: auth.LoggedIn,
    tema_id: int,
):
    tema = temes_q.get_tema_by_id(tema_id)
    if not tema:
        raise HTTPException(status_code=404, detail="Could not find tune")
    tema = links_service.add_links_to_tema(tema)
    return links_fragments.score(
        request=request,
        logged_in=logged_in,
        tema=tema,
    )


@router.get("/api/tema/{tema_id}/editor/link/{link_id}")
def link_editor(
    request: Request,
    logged_in: auth.RequireLogin,
    tema_id: int,
    link_id: int,
):
    link = links_service.get_link_by_id(link_id=link_id, tema_id=tema_id)
    if not link:
        raise HTTPException(status_code=404, detail="Could not find link!")
    return links_fragments.link_editor(
        request=request,
        logged_in=logged_in,
        link=link,
    )


@router.get("/api/tema/{tema_id}/editor/link/{link_id}/url")
def link_editor_url_input(
    request: Request,
    logged_in: auth.RequireLogin,
    tema_id: int,
    link_id: int,
):
    link = links_service.get_link_by_id(link_id=link_id, tema_id=tema_id)
    if not link:
        raise HTTPException(status_code=404, detail="Could not find link!")
    return links_fragments.link_editor_url(
        request=request,
        logged_in=logged_in,
        link=link,
    )


@router.get("/api/tema/{tema_id}/editor/link/{link_id}/file")
def link_editor_file_input(
    request: Request,
    logged_in: auth.RequireLogin,
    tema_id: int,
    link_id: int,
):
    link = links_service.get_link_by_id(link_id=link_id, tema_id=tema_id)
    if not link:
        raise HTTPException(status_code=404, detail="Could not find link!")
    return links_fragments.link_editor_file(
        request=request,
        logged_in=logged_in,
        link=link,
    )
