import logging

logger = logging.getLogger("nebulascrape.transport.http2")


class TransportHTTP2:
    name = "http2"

    def __init__(self, profile_data: dict, **kwargs):
        self.profile_data = profile_data
        self.kwargs = kwargs
        self._client = None

    def _build_client(self):
        try:
            import httpx
            headers = dict(self.profile_data.get("headers", {}))
            self._client = httpx.Client(
                http2=True,
                headers=headers,
                verify=True,
                follow_redirects=True,
            )
            return True
        except ImportError:
            logger.warning("[TransportHTTP2] httpx not installed — HTTP/2 unavailable")
            return False

    def mount_on(self, session):
        if self._build_client():
            session._http2_client = self._client
            logger.debug("[TransportHTTP2] HTTP/2 client mounted")
        else:
            from .http1 import TransportHTTP
            transport = TransportHTTP(self.profile_data)
            transport.mount_on(session)

    def request(self, method: str, url: str, **kwargs):
        if self._client is None:
            self._build_client()
        if self._client:
            return self._client.request(method, url, **kwargs)
        raise RuntimeError("HTTP/2 transport not available")

    def rebuild(self, session):
        if self._client:
            try:
                self._client.close()
            except Exception:
                pass
        self._client = None
        self.mount_on(session)
