"""REQ-FD-004: Centralized MIME detection."""

from __future__ import annotations

import mimetypes
from enum import Enum
from pathlib import Path

_MAGIC_SIGS: list[tuple[bytes, str]] = [
    (b"\x89PNG\r\n\x1a\n", "image/png"),
    (b"\xff\xd8\xff", "image/jpeg"),
    (b"GIF87a", "image/gif"),
    (b"GIF89a", "image/gif"),
    (b"RIFF", "image/webp"),  # RIFF....WEBP — checked further below
    (b"%PDF", "application/pdf"),
    (b"PK\x03\x04", "application/zip"),
    (b"OggS", "audio/ogg"),
]


class MediaKind(str, Enum):
    IMAGE = "image"
    AUDIO = "audio"
    VIDEO = "video"
    DOCUMENT = "document"


_KIND_MAP: dict[str, MediaKind] = {
    "image": MediaKind.IMAGE,
    "audio": MediaKind.AUDIO,
    "video": MediaKind.VIDEO,
}


def detect_mime(path: str | Path) -> tuple[str, MediaKind]:
    """
    Detect MIME type using magic bytes first, then filename extension.

    Returns ``(mime_type, MediaKind)``.
    """
    p = Path(path)
    mime: str | None = None

    try:
        header = p.read_bytes()[:16]
        for sig, sig_mime in _MAGIC_SIGS:
            if header.startswith(sig):
                if sig_mime == "image/webp" and b"WEBP" not in header[:12]:
                    continue
                mime = sig_mime
                break
    except Exception:
        pass

    if not mime:
        guessed, _ = mimetypes.guess_type(str(p))
        mime = guessed or "application/octet-stream"

    major = mime.split("/", 1)[0]
    kind = _KIND_MAP.get(major, MediaKind.DOCUMENT)
    return mime, kind
