"""Helpers for file type recognition."""

from __future__ import annotations

import mimetypes
from pathlib import Path

_ARCHIVE_MIME_BY_SUFFIX: list[tuple[str, str]] = [
    (".tar.gz", "application/x-tar"),
    (".tgz", "application/x-tar"),
    (".tar.bz2", "application/x-tar"),
    (".tbz2", "application/x-tar"),
    (".tar.xz", "application/x-tar"),
    (".txz", "application/x-tar"),
    (".zip", "application/zip"),
    (".tar", "application/x-tar"),
    (".gz", "application/gzip"),
    (".bz2", "application/x-bzip2"),
    (".xz", "application/x-xz"),
]


def _detect_archive_mime_by_suffix(path: Path) -> str | None:
    """Return archive MIME type based on filename suffix patterns."""
    lower_name = path.name.lower()
    for suffix, mime_type in _ARCHIVE_MIME_BY_SUFFIX:
        if lower_name.endswith(suffix):
            return mime_type
    return None


def detect_mime_type(path: Path) -> str:
    """Detect MIME type for a filesystem path."""
    if path.is_dir():
        return "inode/directory"

    mime_type, _ = mimetypes.guess_type(str(path))
    if mime_type:
        return mime_type

    archive_mime = _detect_archive_mime_by_suffix(path)
    if archive_mime:
        return archive_mime

    return "application/octet-stream"


def classify_file_type(mime_type: str) -> str:
    """Map MIME type to a coarse file-type category."""
    if mime_type == "inode/directory":
        return "directory"

    major_type = mime_type.split("/", maxsplit=1)[0]
    if major_type in {"image", "video", "audio", "text"}:
        return major_type

    if mime_type in {"application/pdf", "application/json", "application/xml"}:
        return "document"

    return "other"


def summarize_file_types(paths: list[Path]) -> str:
    """Build a compact summary of file types for a path list."""
    counts: dict[str, int] = {}
    for path in paths:
        mime_type = detect_mime_type(path)
        category = classify_file_type(mime_type)
        counts[category] = counts.get(category, 0) + 1

    if not counts:
        return ""

    ordered = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
    return ", ".join(f"{count} {category}" for category, count in ordered)
