from curl_cffi.requests import AsyncSession
from src.core.session import SessionState
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class CurlClient:
    """
    High-performance extraction client using curl_cffi.
    Mimics the TLS fingerprint and header profile of the browser session.
    """
    def __init__(self, session_state: SessionState):
        self.session_state = session_state
        self.session = None

    async def __aenter__(self):
        await self.initialize()
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.close()

    async def initialize(self) -> None:
        """
        Configure the curl_cffi session with matching fingerprint.
        """
        logger.info("Initializing CurlClient...")
        
        # impersonate argument controls TLS Client Hello
        # impersonate argument controls TLS Client Hello
        # 'chrome124' matches our hardcoded Camoufox build in this MVP
        self.session = AsyncSession(impersonate=self.session_state.tls_fingerprint)
        
        # 1. Inject Cookies
        for cookie in self.session_state.cookies:
            # curl_cffi expects specific arguments for setting cookies if done manually,
            # or we can use the cookies parameter in requests.
            # But AsyncSession has a cookie jar.
            self.session.cookies.set(
                name=cookie['name'],
                value=cookie['value'],
                domain=cookie['domain'],
                path=cookie.get('path', '/')
                # secure is handled by protocol
            )
            
        # 2. Set Headers
        # We need to explicitly set headers that match the browser
        self.session.headers = {
            "User-Agent": self.session_state.user_agent,
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "Accept-Language": "en-US,en;q=0.9",
            # Add sec-ch-ua derivation here if strict mode
        }
        
        logger.info(f"CurlClient initialized with impersonation: {self.session_state.tls_fingerprint}")

    async def close(self) -> None:
        if self.session:
            await self.session.close()

    async def fetch(self, url: str) -> str:
        """
        Execute a GET request using the impersonated session.
        """
        if not self.session:
            raise RuntimeError("Client not initialized")
            
        logger.info(f"Fetching {url}...")
        response = await self.session.get(url)
        logger.info(f"Response status: {response.status_code}")
        return response.text
