import aiohttp
from typing import Optional, List
from .session import ShadeySession


class Shadey:
    def __init__(self, api_key: str, base_url: str = "https://api.shadey.dev"):
        self.api_key = api_key
        self.base_url = base_url.rstrip("/")
        self._http: Optional[aiohttp.ClientSession] = None

    async def __aenter__(self):
        self._http = aiohttp.ClientSession(
            headers={"Authorization": f"Bearer {self.api_key}"}
        )
        return self

    async def __aexit__(self, *args):
        if self._http:
            await self._http.close()

    def _ensure_http(self):
        if not self._http:
            self._http = aiohttp.ClientSession(
                headers={"Authorization": f"Bearer {self.api_key}"}
            )

    async def _request(self, method: str, path: str, **kwargs) -> dict:
        self._ensure_http()
        async with self._http.request(method, f"{self.base_url}{path}", **kwargs) as resp:
            if resp.status == 204:
                return {}
            data = await resp.json()
            if resp.status >= 400:
                raise ShadeyError(resp.status, data.get("error", str(data)))
            return data

    async def session(
        self,
        stealth: str = "full",
        proxy: Optional[str] = None,
        profile: Optional[str] = None,
    ) -> "ShadeySession":
        payload = {"stealth": stealth}
        if proxy:
            payload["proxy"] = proxy
        if profile:
            payload["profile_name"] = profile

        data = await self._request("POST", "/v1/sessions", json=payload)
        return ShadeySession(
            id=data["id"],
            cdp_url=data["cdp_url"],
            client=self,
        )

    async def sessions(self) -> List[dict]:
        return await self._request("GET", "/v1/sessions")

    async def health(self) -> dict:
        self._ensure_http()
        async with self._http.get(f"{self.base_url}/health") as resp:
            return await resp.json()

    async def usage(self) -> dict:
        return await self._request("GET", "/v1/usage")

    async def profiles(self) -> list:
        data = await self._request("GET", "/v1/profiles")
        return data.get("profiles", [])

    async def delete_profile(self, name: str):
        await self._request("DELETE", f"/v1/profiles/{name}")

    async def close(self):
        if self._http:
            await self._http.close()
            self._http = None


class ShadeyError(Exception):
    def __init__(self, status: int, message: str):
        self.status = status
        self.message = message
        super().__init__(f"[{status}] {message}")
