from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import Response
from ...shared.config.logging_config import get_logger
from ...shared.config.settings import settings
logger = get_logger(__name__)

class SecurityHeadersMiddleware(BaseHTTPMiddleware):

    async def dispatch(self, request: Request, call_next):
        response = await call_next(request)
        security_headers = {'X-Content-Type-Options': 'nosniff', 'X-Frame-Options': 'DENY', 'X-XSS-Protection': '1; mode=block', 'Referrer-Policy': 'strict-origin-when-cross-origin', 'Permissions-Policy': 'geolocation=(), microphone=(), camera=()'}
        # Allow cross-origin resource sharing for uploads/images
        # This is needed for images to load from different origins in development
        if '/uploads/' in str(request.url):
            security_headers.setdefault('Cross-Origin-Resource-Policy', 'cross-origin')
        else:
            security_headers.setdefault('Cross-Origin-Resource-Policy', 'same-origin')
        if settings.is_production:
            # Enhanced CSP with stricter directives
            # Using 'strict-dynamic' for better security with nonce-based scripts
            # Note: For React/Vite, consider implementing nonce-based CSP in the future
            # Current policy balances security with framework requirements
            security_headers['Content-Security-Policy'] = (
                "default-src 'self'; "
                "script-src 'self' 'strict-dynamic' https://js.stripe.com; "
                "script-src-elem 'self' 'unsafe-inline' https://js.stripe.com; "  # Allow inline scripts for Vite/React
                "style-src 'self' 'unsafe-inline'; "  # Required for React/Vite
                "img-src 'self' data: https:; "
                "font-src 'self' data:; "
                "connect-src 'self' https: https://js.stripe.com https://hooks.stripe.com; "
                "frame-src 'self' https://js.stripe.com https://hooks.stripe.com; "
                "base-uri 'self'; "
                "form-action 'self'; "
                "frame-ancestors 'none'; "
                "object-src 'none'; "
                "upgrade-insecure-requests; "
                "block-all-mixed-content"  # Block mixed HTTP/HTTPS content
            )
            # HSTS with preload directive (only add preload if domain is ready for it)
            # Preload requires manual submission to hstspreload.org
            # Include preload directive only if explicitly enabled
            hsts_directive = 'max-age=31536000; includeSubDomains'
            if getattr(settings, 'HSTS_PRELOAD_ENABLED', False):
                hsts_directive += '; preload'
            security_headers['Strict-Transport-Security'] = hsts_directive
        for header, value in security_headers.items():
            response.headers[header] = value
        return response