"""X OAuth 2.0 PKCE adapter for user-context Ads API access."""

import httpx


class XAdsOAuthError(Exception):
    def __init__(self, code="provider_unavailable"):
        self.code = code
        super().__init__(code)


class XAdsOAuthClient:
    async def token(self, **data):
        async with httpx.AsyncClient(timeout=20) as client:
            try:
                response = await client.post("https://api.x.com/2/oauth2/token", data=data)
                payload = response.json()
            except (httpx.HTTPError, ValueError):
                raise XAdsOAuthError() from None
        if response.is_error:
            code = payload.get("error")
            raise XAdsOAuthError(code if code == "invalid_grant" else "provider_unavailable")
        if not payload.get("access_token"):
            raise XAdsOAuthError()
        return payload

    async def userinfo(self, token):
        async with httpx.AsyncClient(timeout=20) as client:
            try:
                response = await client.get(
                    "https://api.x.com/2/users/me",
                    headers={"Authorization": f"Bearer {token['access_token']}"},
                )
                response.raise_for_status()
                payload = response.json()
            except (httpx.HTTPError, ValueError):
                raise XAdsOAuthError() from None
        subject = (payload.get("data") or {}).get("id")
        if not subject:
            raise XAdsOAuthError("identity_not_verified")
        return {"sub": str(subject)}
