from __future__ import annotations

import asyncio

from aegro.api_client import AegroClient


class SyncAegroClient:
    """Synchronous wrapper over async AegroClient for CLI use.

    Creates a fresh AegroClient per call to avoid event loop reuse issues.
    asyncio.run() creates and destroys an event loop each time, so reusing
    an async httpx.AsyncClient across calls would cause 'attached to a
    different loop' errors.
    """

    def __init__(
        self,
        base_url: str = "https://app.aegro.com.br",
        timeout: float = 30.0,
        max_retries: int = 3,
    ):
        self._base_url = base_url
        self._timeout = timeout
        self._max_retries = max_retries

    def _make_client(self) -> AegroClient:
        return AegroClient(
            base_url=self._base_url,
            timeout=self._timeout,
            max_retries=self._max_retries,
        )

    def get(self, path: str, *, api_key: str) -> dict | list | None:
        async def _do() -> dict | list | None:
            client = self._make_client()
            try:
                return await client.get(path, api_key=api_key)
            finally:
                await client.close()

        return asyncio.run(_do())

    def post(self, path: str, *, api_key: str, json_body: dict | None = None) -> dict | list | None:
        async def _do() -> dict | list | None:
            client = self._make_client()
            try:
                return await client.post(path, api_key=api_key, json_body=json_body)
            finally:
                await client.close()

        return asyncio.run(_do())

    def put(self, path: str, *, api_key: str, json_body: dict | None = None) -> dict | list | None:
        async def _do() -> dict | list | None:
            client = self._make_client()
            try:
                return await client.put(path, api_key=api_key, json_body=json_body)
            finally:
                await client.close()

        return asyncio.run(_do())

    def delete(self, path: str, *, api_key: str) -> dict | list | None:
        async def _do() -> dict | list | None:
            client = self._make_client()
            try:
                return await client.delete(path, api_key=api_key)
            finally:
                await client.close()

        return asyncio.run(_do())

    def download(
        self,
        path: str,
        *,
        api_key: str,
        method: str = "GET",
        json_body: dict | None = None,
    ) -> bytes | None:
        async def _do() -> bytes | None:
            client = self._make_client()
            try:
                return await client.download(
                    path, api_key=api_key, method=method, json_body=json_body
                )
            finally:
                await client.close()

        return asyncio.run(_do())
