"""Fracciones Service"""

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


class FraccionesService(SitarAPIBaseService):
    """Service for Fracciones operations"""

    _instance: Optional["FraccionesService"] = None

    @classmethod
    def get_instance(cls) -> "FraccionesService":
        """Get singleton instance"""
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance

    async def search(
        self,
        fraccion: Optional[str] = None,
        nico: Optional[str] = None,
        description: Optional[str] = None,
        nivel: Optional[int] = None,
        skip: int = 0,
        limit: int = 100,
    ) -> List[FraccionesResponse]:
        """Search Mexican tariff fractions"""
        params = {"skip": skip, "limit": min(limit, 1000)}
        if fraccion:
            params["fraccion"] = fraccion
        if nico:
            params["nico"] = nico
        if description:
            params["descripcion"] = description
        if nivel is not None:
            params["nivel"] = nivel

        data = await self._make_request("GET", "/api/v1/fracciones/", params=params)
        return [FraccionesResponse(**item) for item in data]

    async def get_by_id(self, sysid: int) -> FraccionesResponse:
        """Get single Fraccion record by SYSID"""
        data = await self._make_request("GET", f"/api/v1/fracciones/{sysid}")
        return FraccionesResponse(**data)

    @classmethod
    def search_sync(
        cls,
        fraccion: Optional[str] = None,
        nico: Optional[str] = None,
        description: Optional[str] = None,
        nivel: Optional[int] = None,
        skip: int = 0,
        limit: int = 100,
    ) -> List[FraccionesResponse]:
        """Search Mexican tariff fractions (sync wrapper for use in Celery/sync context)."""
        service = cls.get_instance()
        return asyncio.run(
            service.search(
                fraccion=fraccion,
                nico=nico,
                description=description,
                nivel=nivel,
                skip=skip,
                limit=limit,
            )
        )
