import os
import re
from core.exceptions import ValidationError

# Allowed file extensions and magic headers
ALLOWED_MIME_SIGNATURES = {
    "png": b"\x89PNG\r\n\x1a\n",
    "jpg": b"\xff\xd8\xff",
    "jpeg": b"\xff\xd8\xff",
    "webp": b"RIFF",  # Followed by WEBP at offset 8
    "pdf": b"%PDF",
    "json": b"{",  # JSON text payload
}

MAX_FILE_SIZE_BYTES = 10 * 1024 * 1024  # 10 MB default limit


def secure_filename(filename: str) -> str:
    """
    Sanitizes filename to prevent directory traversal and filesystem attacks.
    Strips directory separators, relative path markers ('..'), null bytes, and non-printable characters.
    """
    if not filename:
        return "unnamed_file"

    # Remove null bytes
    cleaned = filename.replace("\x00", "")
    # Normalize backslashes to forward slashes then take basename
    cleaned = os.path.basename(cleaned.replace("\\", "/"))
    # Remove path traversal characters
    cleaned = re.sub(r"\.\.+", "", cleaned)
    # Only allow alphanumeric, dashes, underscores, and dots
    cleaned = re.sub(r"[^a-zA-Z0-9._-]", "_", cleaned)
    # Ensure it's not empty or just dots
    cleaned = cleaned.strip("._")
    return cleaned or "secure_file"


def validate_file_content(
    filename: str,
    content: bytes,
    allowed_extensions: set[str] | None = None,
    max_size_bytes: int = MAX_FILE_SIZE_BYTES,
) -> str:
    """
    Validates uploaded file content against size, extension whitelist, and magic byte signatures.
    Raises ValidationError if any security check fails. Returns sanitized safe filename.
    """
    if not content:
        raise ValidationError("Uploaded file cannot be empty")

    if len(content) > max_size_bytes:
        raise ValidationError(
            f"File exceeds maximum allowed size of {max_size_bytes / (1024 * 1024):.1f} MB"
        )

    safe_name = secure_filename(filename)
    ext = safe_name.rsplit(".", 1)[-1].lower() if "." in safe_name else ""

    if not ext:
        raise ValidationError("File must have a valid extension")

    # Extension whitelist check
    allowed = allowed_extensions or {"png", "jpg", "jpeg", "webp", "pdf", "json"}
    if ext not in allowed:
        raise ValidationError(
            f"File extension '.{ext}' is not permitted. Allowed extensions: {', '.join(sorted(allowed))}"
        )

    # Magic byte verification (defense against extension spoofing)
    if ext in ("png", "jpg", "jpeg", "pdf"):
        expected_sig = ALLOWED_MIME_SIGNATURES[ext]
        if not content.startswith(expected_sig):
            raise ValidationError(
                f"File content does not match expected binary format for '.{ext}'"
            )
    elif ext == "webp":
        if not (content.startswith(b"RIFF") and len(content) > 12 and content[8:12] == b"WEBP"):
            raise ValidationError("File content is not a valid WEBP image")
    elif ext == "json":
        # Ensure it starts with valid JSON structure
        stripped = content.strip()
        if not (stripped.startswith(b"{") or stripped.startswith(b"[")):
            raise ValidationError("File content is not valid JSON")

    return safe_name
