from __future__ import annotations

from advanced_alchemy.service import SQLAlchemyAsyncRepositoryService
from advanced_alchemy.repository import SQLAlchemyAsyncRepository

from chitai.database.models.kosync_progress import KosyncProgress


class KosyncProgressService(SQLAlchemyAsyncRepositoryService[KosyncProgress]):
    """Service for managing KOReader sync progress."""

    class Repo(SQLAlchemyAsyncRepository[KosyncProgress]):
        """Repository for KosyncProgress entities."""

        model_type = KosyncProgress

    repository_type = Repo

    async def get_by_document_hash(
        self, user_id: int, document: str
    ) -> KosyncProgress | None:
        """Get progress for a specific document and user."""
        return await self.get_one_or_none(
            KosyncProgress.user_id == user_id,
            KosyncProgress.document == document,
        )

    async def upsert_progress(
        self,
        user_id: int,
        book_id: int,
        document: str,
        progress: str | None,
        percentage: float,
        device: str | None = None,
        device_id: str | None = None,
    ) -> KosyncProgress:
        """Create or update progress for a document."""
        existing = await self.get_by_document_hash(user_id, document)

        data = {
            "user_id": user_id,
            "book_id": book_id,
            "document": document,
            "progress": progress,
            "percentage": percentage,
            "device": device,
            "device_id": device_id,
        }

        if existing:
            return await self.update(data, item_id=existing.id)
        return await self.create(data)
