"""
Static File Serving Routes
Endpoints for serving uploaded files and images
"""
from fastapi import APIRouter, HTTPException
from fastapi.responses import FileResponse
import os
from pathlib import Path

router = APIRouter(tags=["Static Files"])


@router.get("/images/{file_path:path}")
async def serve_image(file_path: str):
    """
    Serve images given a relative file path.
    Validates that the path starts with allowed directories (shared document store), e.g.:
    - document_images_/file_data/...
    - extracted_images_/file_data/...
    - uploaded_files_/file_data/...
    
    Args:
        file_path: Relative path to the image (e.g., "extracted_images_/extracted_images_agent1/image.png")
    
    Returns:
        FileResponse with the image file
    """
    try:
        # Security check & Path Extraction
        allowed_prefixes = ["document_images_", "extracted_images_", "uploaded_files_"]
        valid_path = None
        
        # Remove any URL scheme and domain if present
        path_to_check = file_path
        if "://" in file_path:
            # Extract disk path after the images serve prefix (legacy prefixes still accepted)
            for marker in ("/api/images/", "/api/static/images/", "/static/images/"):
                if marker in file_path:
                    path_to_check = file_path.split(marker)[-1]
                    break
        
        # Now check for allowed prefixes
        for prefix in allowed_prefixes:
            if path_to_check.startswith(prefix):
                valid_path = path_to_check
                break
            # Also check if prefix appears later in the path
            index = path_to_check.find(prefix)
            if index != -1:
                valid_path = path_to_check[index:]
                break
        
        if not valid_path:
            raise HTTPException(status_code=403, detail="Access denied: Invalid file path")
        
        # Use the extracted valid path
        file_path = valid_path
        
        # Construct full file path
        # The file_path includes the folder name, so we just join it with current working directory
        full_path = Path(os.getcwd()) / file_path
        
        # Security check: ensure path traversal is not attempted
        try:
            full_path = full_path.resolve()
            cwd = Path(os.getcwd()).resolve()
            if not str(full_path).startswith(str(cwd)):
                raise HTTPException(status_code=403, detail="Access denied: Path traversal detected")
        except Exception:
            raise HTTPException(status_code=403, detail="Invalid file path")
        
        # Check if file exists
        if not full_path.exists() or not full_path.is_file():
            raise HTTPException(status_code=404, detail="Image not found")
        
        # Determine media type based on file extension
        ext = full_path.suffix.lower()
        media_types = {
            '.png': 'image/png',
            '.jpg': 'image/jpeg',
            '.jpeg': 'image/jpeg',
            '.gif': 'image/gif',
            '.bmp': 'image/bmp',
            '.webp': 'image/webp',
            '.svg': 'image/svg+xml'
        }
        media_type = media_types.get(ext, 'application/octet-stream')
        
        return FileResponse(
            path=str(full_path),
            media_type=media_type,
            filename=full_path.name
        )
    
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error serving image: {str(e)}")


@router.get("/uploads/{file_path:path}")
async def serve_file(file_path: str):
    """
    Serve files given a relative file path.
    
    Args:
        file_path: Relative path to the file (e.g., "uploaded_files_/file_data/...")
    
    Returns:
        FileResponse with the file
    """
    try:
        # Security check & Path Extraction
        allowed_prefixes = ["uploaded_files_"]
        valid_path = None
        
        # Remove any URL scheme and domain if present
        path_to_check = file_path
        if "://" in file_path:
            for marker in ("/api/uploads/", "/api/static/files/", "/static/files/", "/api/files/", "/files/"):
                if marker in file_path:
                    path_to_check = file_path.split(marker)[-1]
                    break
        
        # Now check for allowed prefixes
        for prefix in allowed_prefixes:
            if path_to_check.startswith(prefix):
                valid_path = path_to_check
                break
            # Also check if prefix appears later in the path
            index = path_to_check.find(prefix)
            if index != -1:
                valid_path = path_to_check[index:]
                break
        
        if not valid_path:
            raise HTTPException(status_code=403, detail="Access denied: Invalid file path")
        
        # Use the extracted valid path
        file_path = valid_path
        
        # Construct full file path
        full_path = Path(os.getcwd()) / file_path
        
        # Security check: ensure path traversal is not attempted
        try:
            full_path = full_path.resolve()
            cwd = Path(os.getcwd()).resolve()
            if not str(full_path).startswith(str(cwd)):
                raise HTTPException(status_code=403, detail="Access denied: Path traversal detected")
        except Exception:
            raise HTTPException(status_code=403, detail="Invalid file path")
        
        # Check if file exists
        if not full_path.exists() or not full_path.is_file():
            raise HTTPException(status_code=404, detail="File not found")
        
        return FileResponse(
            path=str(full_path),
            filename=full_path.name
        )
    
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error serving file: {str(e)}")