"""FraccionesAnteriores Service"""

import asyncio
from typing import Optional, List
from ..common import SitarAPIBaseService
from .schemas import FraccionesAnterioresResponse


class FraccionesAnterioresService(SitarAPIBaseService):
    _instance: Optional["FraccionesAnterioresService"] = None

    @classmethod
    def get_instance(cls) -> "FraccionesAnterioresService":
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance

    async def search(
        self,
        fraccion_actual: Optional[str] = None,
        fraccion_anterior: Optional[str] = None,
        skip: int = 0,
        limit: int = 100,
    ) -> List[FraccionesAnterioresResponse]:
        params = {"skip": skip, "limit": min(limit, 1000)}
        if fraccion_actual:
            params["fraccion_actual"] = fraccion_actual
        if fraccion_anterior:
            params["fraccion_anterior"] = fraccion_anterior
        data = await self._make_request(
            "GET", "/api/v1/fracciones-anteriores/", params=params
        )
        return [FraccionesAnterioresResponse(**item) for item in data]

    async def get_by_id(self, sysid: int) -> FraccionesAnterioresResponse:
        data = await self._make_request("GET", f"/api/v1/fracciones-anteriores/{sysid}")
        return FraccionesAnterioresResponse(**data)

    @classmethod
    def search_sync(
        cls,
        fraccion_actual: Optional[str] = None,
        fraccion_anterior: Optional[str] = None,
        skip: int = 0,
        limit: int = 100,
    ) -> List[FraccionesAnterioresResponse]:
        """Search historical fractions (sync wrapper for use in Celery/sync context)."""
        service = cls.get_instance()
        return asyncio.run(
            service.search(
                fraccion_actual=fraccion_actual,
                fraccion_anterior=fraccion_anterior,
                skip=skip,
                limit=limit,
            )
        )
