"""Safe filesystem scanning helpers."""

from __future__ import annotations

import os
import pathlib
from typing import Any

IGNORE_DIRS = {
    ".git",
    "__pycache__",
    ".venv",
    "venv",
    "node_modules",
    ".tox",
    "runs",
    ".mypy_cache",
    ".pytest_cache",
}
IGNORE_FILES = {".DS_Store", "Thumbs.db"}


def scan_repo(root: pathlib.Path) -> dict[str, Any]:
    """Walk repo and produce a deterministic map of files and counts."""
    files: list[str] = []
    dirs: list[str] = []
    py_count = 0

    for dirpath, dirnames, filenames in os.walk(root):
        dirnames[:] = [d for d in sorted(dirnames) if d not in IGNORE_DIRS]
        rel_dir = os.path.relpath(dirpath, root)
        if rel_dir != ".":
            dirs.append(rel_dir.replace("\\", "/"))
        for fname in sorted(filenames):
            if fname in IGNORE_FILES:
                continue
            rel = os.path.relpath(os.path.join(dirpath, fname), root).replace("\\", "/")
            files.append(rel)
            if fname.endswith(".py"):
                py_count += 1

    return {
        "repo_root": str(root),
        "files": files,
        "directories": dirs,
        "total_files": len(files),
        "total_directories": len(dirs),
        "python_file_count": py_count,
    }


def search_files(root: pathlib.Path, pattern: str) -> list[str]:
    """Simple glob search relative to root."""
    matches = []
    for p in root.rglob(pattern):
        rel = p.relative_to(root).as_posix()
        skip = any(part in IGNORE_DIRS for part in p.relative_to(root).parts)
        if not skip:
            matches.append(rel)
    return sorted(matches)
