from typing import Dict, Any, List
import re
from .session import SessionState

class HandoverValidator:
    """
    Validates that a session state is suitable for handover and that
    the target extractor configuration matches the source browser's fingerprint.
    """

    @staticmethod
    def validate_session_consistency(session: SessionState) -> bool:
        """
        Check if the session state itself is internally consistent.
        """
        # 1. Check User-Agent vs TLS Fingerprint (Rough check)
        # simplistic check: if chrome in UA, fingerprint should start with chrome
        ua = session.user_agent.lower()
        fp = session.tls_fingerprint.lower()
        
        if "chrome" in ua and "chrome" not in fp:
            return False
        if "firefox" in ua and "firefox" not in fp and "safari" not in fp: 
            # some variance allowed, but generally should match
            pass 
            
        return True

    @staticmethod
    def derive_sec_ch_ua(user_agent: str) -> str:
        """
        Derive sec-ch-ua header value from User-Agent string.
        This is a critical part of the handover to ensuring the extractor
        looks like the browser.
        """
        # Example UA: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36
        match = re.search(r'Chrome/(\d+)\.', user_agent)
        if match:
            major_version = match.group(1)
            # Standard Chrome pattern
            return f'"Not_A Brand";v="8", "Chromium";v="{major_version}", "Google Chrome";v="{major_version}"'
            
        # Fallback or other browsers
        return '"Not_A Brand";v="99", "Chromium";v="120"' # Default fallback
