"""File discovery utilities for ADFMentor."""

from pathlib import Path
from typing import Optional


ADF_SUBDIRS = {"pipeline", "dataset", "linkedservice", "trigger", "dataflow"}


def get_file_by_type(directory: str, extension: str) -> Optional[str]:
    """Find the first file with the given extension in a directory.

    Args:
        directory: Path to the directory to search
        extension: File extension to search for (e.g., '.json', '.pdf')

    Returns:
        Filename if found, None otherwise
    """
    try:
        dir_path = Path(directory).resolve()

        if not dir_path.exists() or not dir_path.is_dir():
            return None

        extension_lower = extension.lower()
        # Use rglob to finding the file regardless of directory depth
        for file in dir_path.rglob(f"*{extension_lower}"):
            if file.is_file():
                # return relative path to original directory so core can locate it properly
                return str(file.relative_to(dir_path))

        return None
    except (OSError, PermissionError):
        return None


def is_adf_project(directory: str) -> bool:
    """Check if a directory looks like an ADF project.

    An ADF project typically has subdirectories like pipeline/,
    dataset/, linkedService/, trigger/, or dataflow/.

    Args:
        directory: Path to the directory to check

    Returns:
        True if the directory contains ADF resource subdirectories
    """
    try:
        dir_path = Path(directory).resolve()
        if not dir_path.exists() or not dir_path.is_dir():
            return False

        for child in dir_path.iterdir():
            if child.is_dir() and child.name.lower() in ADF_SUBDIRS:
                return True

        return False
    except (OSError, PermissionError):
        return False
