import logging
from typing import Optional

from .http1 import TransportHTTP
from .http2 import TransportHTTP2
from .headless import TransportHeadless
from ..fingerprints import get_profile

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

TRANSPORT_TIERS = ["http1", "http2", "headless"]


class TransportManager:
    def __init__(self, profile_name: str = "chrome_windows", mode: str = "auto"):
        self.profile_name = profile_name
        self.mode = mode
        self._profile_data = get_profile(profile_name)
        self._current_tier_index: int = 0
        self._success_counts: dict = {t: 0 for t in TRANSPORT_TIERS}
        self._fail_counts: dict = {t: 0 for t in TRANSPORT_TIERS}
        self._active_transport = None
        self._build_transport()

    def _build_transport(self):
        tier = self._current_tier()
        if tier == "http2":
            self._active_transport = TransportHTTP2(self._profile_data)
        elif tier == "headless":
            self._active_transport = TransportHeadless(self.profile_name)
        else:
            self._active_transport = TransportHTTP(self._profile_data)
        logger.debug(f"[TransportManager] Active transport: {tier}")

    def _current_tier(self) -> str:
        if self.mode != "auto":
            return self.mode
        return TRANSPORT_TIERS[min(self._current_tier_index, len(TRANSPORT_TIERS) - 1)]

    def mount_on(self, session):
        self._active_transport.mount_on(session)

    def escalate(self, session):
        if self._current_tier_index < len(TRANSPORT_TIERS) - 1:
            self._current_tier_index += 1
            self._build_transport()
            self._active_transport.mount_on(session)
            logger.info(f"[TransportManager] Escalated to: {self._current_tier()}")
        else:
            logger.warning("[TransportManager] Already at maximum transport tier (headless)")

    def rebuild(self, session):
        self._active_transport.rebuild(session)

    def record_success(self):
        self._success_counts[self._current_tier()] += 1

    def record_failure(self):
        tier = self._current_tier()
        self._fail_counts[tier] += 1
        total = self._fail_counts[tier]
        if total >= 3:
            logger.info(f"[TransportManager] Transport '{tier}' has {total} failures — auto-escalating")
            return True
        return False

    @property
    def current_name(self) -> str:
        return self._current_tier()
