from __future__ import annotations

from typing import Annotated

from litestar import Controller, get, put
from litestar.exceptions import HTTPException
from litestar.status_codes import HTTP_403_FORBIDDEN
from litestar.response import Response
from litestar.params import Parameter
from litestar.di import Provide

from chitai.database import models as m
from chitai.schemas.kosync import KosyncProgressUpdate, KosyncProgressRead
from chitai.services.book import BookService
from chitai.services.kosync_progress import KosyncProgressService
from chitai.services.filters.book import FileHashFilter
from chitai.services import dependencies as deps
from chitai.middleware.kosync_auth import kosync_api_key_auth


class KosyncController(Controller):
    """Controller for syncing progress with KOReader devices."""

    middleware = [kosync_api_key_auth]

    dependencies = {
        "kosync_progress_service": Provide(deps.provide_kosync_progress_service),
        "book_service": Provide(deps.provide_book_service),
        "user": Provide(deps.provide_user_via_kosync_auth),
    }

    @put("/syncs/progress")
    async def upload_progress(
        self,
        data: KosyncProgressUpdate,
        book_service: BookService,
        kosync_progress_service: KosyncProgressService,
        user: m.User,
    ) -> None:
        """Upload book progress from a KOReader device."""
        book = await book_service.get_one(FileHashFilter([data.document]))

        await kosync_progress_service.upsert_progress(
            user_id=user.id,
            book_id=book.id,
            document=data.document,
            progress=data.progress,
            percentage=data.percentage,
            device=data.device,
            device_id=data.device_id,
        )

    @get("/syncs/progress/{document_id:str}")
    async def get_progress(
        self,
        document_id: str,
        kosync_progress_service: KosyncProgressService,
        user: m.User,
    ) -> KosyncProgressRead:
        """Return the Kosync progress record associated with the given document."""
        progress = await kosync_progress_service.get_by_document_hash(user.id, document_id)

        if not progress:
            raise HTTPException(status_code=404, detail="No progress found for document")

        return KosyncProgressRead(
            document=progress.document,
            progress=progress.progress,
            percentage=progress.percentage,
            device=progress.device,
            device_id=progress.device_id,
        )

    @get("/users/auth")
    async def authorize(
        self, _api_key: Annotated[str, Parameter(header="X-AUTH-USER")]
    ) -> Response[dict[str, str]]:
        """Verify authentication (handled by middleware)."""
        return Response(status_code=200, content={"authorized": "OK"})

    @get("/users/register")
    async def register(self) -> None:
        """User registration endpoint - disabled."""
        raise HTTPException(
            detail="User accounts must be created via the main application",
            status_code=HTTP_403_FORBIDDEN,
        )
    
    

