"""
Security headers check module
"""
from tests.utils.logger import Logger
from tests.utils.http_utils import HTTPUtils


class SecurityHeadersCheck:
    """Check security headers on API responses"""
    
    def __init__(self, logger: Logger, base_url: str = "http://localhost:8000", version: str = "unknown"):
        self.logger = logger
        self.version = version
        self.http_utils = HTTPUtils(logger, base_url)
    
    def run_all_checks(self) -> bool:
        """Run all security header checks"""
        self.logger.subheader(f"Security Headers Check (v{self.version})")
        
        all_ok = True
        
        # Check security headers on health endpoint
        if not self._check_security_headers():
            all_ok = False
        
        if all_ok:
            self.logger.success("SECURITY", "All security headers checks passed")
        else:
            self.logger.warning("SECURITY", "Some security headers are missing (recommended for production)")
        
        return all_ok
    
    def _check_security_headers(self) -> bool:
        """Check if important security headers are set"""
        self.logger.info("SECURITY", "Checking security headers...")
        
        # Make a request to check headers
        success, status_code, response = self.http_utils.get("/api/health")
        
        if not success:
            self.logger.warning("SECURITY", "Failed to check headers (request failed)")
            return True  # Not critical for development
        
        # Get headers from the last response
        headers = self.http_utils.get_last_headers()
        
        if not headers:
            self.logger.warning("SECURITY", "Failed to get headers")
            return True  # Not critical for development
        
        # Check important security headers
        important_headers = {
            "X-Content-Type-Options": "nosniff",
            "X-Frame-Options": ["DENY", "SAMEORIGIN"],
            "X-XSS-Protection": "1; mode=block",
        }
        
        optional_headers = {
            "Content-Security-Policy": None,  # Value not checked, just presence
            "Strict-Transport-Security": None,  # Value not checked, just presence
        }
        
        missing_critical = []
        missing_optional = []
        
        for header_name, expected_values in important_headers.items():
            header_value = headers.get(header_name.lower())
            if header_value:
                if isinstance(expected_values, list):
                    if any(val in header_value for val in expected_values):
                        self.logger.success("SECURITY", f"{header_name}: set ✓")
                    else:
                        self.logger.warning("SECURITY", f"{header_name}: set but value may not be optimal")
                        missing_optional.append(header_name)
                else:
                    if expected_values in header_value:
                        self.logger.success("SECURITY", f"{header_name}: set ✓")
                    else:
                        self.logger.warning("SECURITY", f"{header_name}: set but value may not be optimal")
                        missing_optional.append(header_name)
            else:
                self.logger.warning("SECURITY", f"{header_name}: not set")
                missing_critical.append(header_name)
        
        for header_name in optional_headers.keys():
            header_value = headers.get(header_name.lower())
            if header_value:
                self.logger.success("SECURITY", f"{header_name}: set ✓")
            else:
                self.logger.info("SECURITY", f"{header_name}: not set (optional for development)")
                missing_optional.append(header_name)
        
        if not missing_critical:
            self.logger.success("SECURITY", "All critical security headers are set ✓")
        
        return True  # Not critical for development, always return True
