import logging

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

_IMPERSONATION_MAP = {
    "chrome_windows": "chrome120",
    "chrome_linux": "chrome120",
    "firefox": "firefox121",
    "mobile": "chrome120",
}


class TransportHeadless:
    name = "headless"

    def __init__(self, profile_name: str = "chrome_windows", **kwargs):
        self.profile_name = profile_name
        self.kwargs = kwargs
        self._session = None

    def _build_session(self):
        try:
            import curl_cffi.requests as curl_req
            impersonate = _IMPERSONATION_MAP.get(self.profile_name, "chrome120")
            self._session = curl_req.Session(impersonate=impersonate)
            logger.debug(f"[TransportHeadless] curl_cffi session built with impersonate={impersonate}")
            return True
        except ImportError:
            logger.warning("[TransportHeadless] curl_cffi not installed — headless transport unavailable")
            return False

    def mount_on(self, session):
        if self._build_session():
            session._headless_client = self._session
            logger.debug("[TransportHeadless] Headless client mounted as fallback")
        else:
            logger.warning("[TransportHeadless] No headless backend available — falling back to HTTP1")
            from .http1 import TransportHTTP
            from ..fingerprints import get_profile
            profile_data = get_profile(self.profile_name)
            t = TransportHTTP(profile_data)
            t.mount_on(session)

    def request(self, method: str, url: str, **kwargs):
        if self._session is None:
            self._build_session()
        if self._session:
            return self._session.request(method, url, **kwargs)
        raise RuntimeError("Headless transport unavailable — install curl_cffi")

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