"""TLS fingerprint bypass — use curl_cffi or tls_client if available for JA3 spoofing."""

import logging

logger = logging.getLogger("iploop.tls")

# Try curl_cffi first (best JA3 spoofing), then tls_client, then fallback to requests
TLS_ENGINE = None

try:
    import curl_cffi.requests as curl_requests
    TLS_ENGINE = "curl_cffi"
    logger.debug("TLS engine: curl_cffi (JA3 spoofing enabled)")
except ImportError:
    try:
        import tls_client
        TLS_ENGINE = "tls_client"
        logger.debug("TLS engine: tls_client (JA3 spoofing enabled)")
    except ImportError:
        TLS_ENGINE = "requests"
        logger.debug("TLS engine: requests (no JA3 spoofing - install curl_cffi for better anti-detection)")


BROWSER_PROFILES = [
    "chrome_120", "chrome_121", "chrome_122", "chrome_123",
    "chrome_124", "chrome_125", "chrome_126",
]


def tls_get(url, headers=None, proxies=None, timeout=15, cookies=None):
    """
    Fetch URL with TLS fingerprint spoofing if available.
    Falls back to regular requests if no TLS library installed.
    
    Returns a response object with .text, .status_code, .headers
    """
    import random
    
    if TLS_ENGINE == "curl_cffi":
        profile = random.choice(BROWSER_PROFILES)
        try:
            resp = curl_requests.get(
                url,
                headers=headers,
                proxies=proxies,
                timeout=timeout,
                cookies=cookies,
                impersonate=profile,
                allow_redirects=True
            )
            return resp
        except Exception as e:
            logger.debug(f"curl_cffi failed ({e}), falling back to requests")
    
    elif TLS_ENGINE == "tls_client":
        try:
            profile = random.choice(BROWSER_PROFILES)
            session = tls_client.Session(client_identifier=profile)
            if proxies:
                proxy = proxies.get("https") or proxies.get("http")
                if proxy:
                    session.proxies = {"http": proxy, "https": proxy}
            resp = session.get(url, headers=headers, timeout_seconds=timeout)
            return resp
        except Exception as e:
            logger.debug(f"tls_client failed ({e}), falling back to requests")
    
    # Fallback: regular requests
    import requests
    return requests.get(url, headers=headers, proxies=proxies, timeout=timeout, cookies=cookies)


def tls_request(method, url, headers=None, proxies=None, timeout=15, data=None, cookies=None):
    """Generic TLS request with fingerprint spoofing."""
    import random
    
    if TLS_ENGINE == "curl_cffi" and method.upper() == "GET":
        return tls_get(url, headers=headers, proxies=proxies, timeout=timeout, cookies=cookies)
    
    # For non-GET or no TLS engine, use requests
    import requests
    return requests.request(method, url, headers=headers, proxies=proxies, 
                           timeout=timeout, data=data, cookies=cookies)


def get_engine():
    """Return current TLS engine name."""
    return TLS_ENGINE
