"""
API versioning middleware for backward compatibility.
"""
from fastapi import Request, HTTPException, status
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import Response
from typing import Callable
import re
from ...shared.config.logging_config import get_logger

logger = get_logger(__name__)

class APIVersioningMiddleware(BaseHTTPMiddleware):
    """Middleware to handle API versioning."""
    
    def __init__(self, app, default_version: str = "v1"):
        super().__init__(app)
        self.default_version = default_version
        self.version_pattern = re.compile(r'/api/v(\d+)/')
    
    async def dispatch(self, request: Request, call_next: Callable) -> Response:
        """Process request and handle versioning."""
        path = request.url.path
        
        # Check if path starts with /api
        if path.startswith('/api'):
            # Extract version from path
            version_match = self.version_pattern.search(path)
            
            if version_match:
                version = version_match.group(1)
                # Store version in request state
                request.state.api_version = f"v{version}"
                # Remove version from path for routing
                new_path = self.version_pattern.sub('/api/', path)
                request.scope['path'] = new_path
            elif path.startswith('/api/') and not path.startswith('/api/v'):
                # No version specified, use default
                request.state.api_version = self.default_version
            else:
                # Health check or other non-versioned endpoints
                request.state.api_version = None
        
        response = await call_next(request)
        
        # Add version header to response
        if hasattr(request.state, 'api_version') and request.state.api_version:
            response.headers['X-API-Version'] = request.state.api_version
        
        return response

