import os
import subprocess
from django.core.exceptions import ValidationError


ALLOWED_EXTENSIONS = {"pdf", "png", "jpg", "jpeg", "webp", "xlsx", "csv", "docx"}

MAGIC_PREFIXES: dict[str, tuple[bytes, ...]] = {
    "pdf": (b"%PDF-",),
    "png": (b"\x89PNG\r\n\x1a\n",),
    "jpg": (b"\xff\xd8\xff",),
    "jpeg": (b"\xff\xd8\xff",),
    "webp": (b"RIFF",),
    "xlsx": (b"PK\x03\x04", b"PK\x05\x06"),
    "docx": (b"PK\x03\x04", b"PK\x05\x06"),
}

DANGEROUS_MARKERS = (b"<script", b"<?php", b"#!/bin/", b"<iframe", b"onerror=", b"onload=")


class SecureUploadValidator:
    """
    Validates uploaded attachments against extension allowlist, size limits, binary magic-byte
    signatures, embedded script/executable payloads, and optional ClamAV scanning.
    """

    DEFAULT_MAX_BYTES = 15 * 1024 * 1024

    @staticmethod
    def validate(uploaded_file, *, allowed_extensions: set[str] | None = None, max_bytes: int = DEFAULT_MAX_BYTES) -> bytes:
        if not uploaded_file:
            raise ValidationError("No uploaded file provided.")

        name = (getattr(uploaded_file, "name", "") or "").strip()
        if "." not in name:
            raise ValidationError("Uploaded file must include a valid file extension.")
        ext = name.rsplit(".", 1)[-1].lower()
        allowed = allowed_extensions or ALLOWED_EXTENSIONS
        if ext not in allowed:
            raise ValidationError(f"Unsupported or disallowed file extension '.{ext}'.")

        raw = uploaded_file.read()
        if not raw:
            raise ValidationError("Uploaded file cannot be empty.")
        if len(raw) > max_bytes:
            raise ValidationError(f"Uploaded file exceeds maximum allowed size ({max_bytes // (1024 * 1024)} MB).")

        prefixes = MAGIC_PREFIXES.get(ext)
        if prefixes and not any(raw.startswith(p) for p in prefixes):
            raise ValidationError(f"File signature does not match '.{ext}' format.")

        if ext in ("csv", "pdf", "png", "jpg", "jpeg", "webp"):
            head_lower = raw[:65536].lower()
            for marker in DANGEROUS_MARKERS:
                if marker in head_lower:
                    raise ValidationError("Uploaded file failed security content inspection.")

        if os.getenv("ENABLE_CLAMAV", "false").lower() == "true":
            proc = subprocess.run(
                ["clamdscan", "--no-summary", "-"],
                input=raw,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                timeout=20,
            )
            if proc.returncode == 1:
                raise ValidationError("Uploaded file rejected by malware scanner.")

        return raw

