"""DICOM file discovery and validation helpers."""

from pathlib import Path

import pydicom
from pydicom.errors import InvalidDicomError

from dicom_mcp.config import MAX_FILES


def _is_dicom_file(file_path: Path) -> bool:
    """Quick check if a file is likely DICOM by checking the preamble.

    DICOM files have a 128-byte preamble followed by 'DICM' magic bytes.
    Files with .dcm extension are assumed to be DICOM without preamble check.
    """
    if file_path.suffix.lower() == ".dcm":
        return True

    try:
        with open(file_path, "rb") as f:
            f.seek(128)
            magic = f.read(4)
            return magic == b"DICM"
    except (OSError, IOError):
        return False


def _find_dicom_files(
    directory: Path,
    recursive: bool = True,
    max_files: int = MAX_FILES,
) -> tuple[list[tuple[Path, pydicom.Dataset]], bool]:
    """Find DICOM files and return paths with pre-read datasets.

    Returns:
        Tuple of (list of (path, dataset) pairs, truncated flag).
        truncated is True if max_files limit was hit.
    """
    results: list[tuple[Path, pydicom.Dataset]] = []
    truncated = False

    pattern = "**/*" if recursive else "*"

    for file_path in sorted(directory.glob(pattern)):
        if not file_path.is_file():
            continue

        if not _is_dicom_file(file_path):
            continue

        try:
            ds = pydicom.dcmread(file_path, stop_before_pixels=True)
            results.append((file_path, ds))
        except (InvalidDicomError, Exception):
            continue

        if len(results) >= max_files:
            truncated = True
            break

    return results, truncated
