from __future__ import annotations

from pathlib import PurePosixPath

_CACHE_DIR_NAMES = {"__pycache__", "app-data", "build", "grafana"}


def should_skip_indexing_path(path: str) -> bool:
    parts = _path_parts(path)
    if not parts:
        return True
    for part in parts:
        if part in _CACHE_DIR_NAMES:
            return True
        if _is_hidden_part(part):
            return True
    return False


def filter_snapshot_files(files: list[dict]) -> list[dict]:
    return [item for item in files if not should_skip_indexing_path(str(item.get("path", "")))]


def filter_changes_for_indexing(changed_files: list[dict]) -> list[dict]:
    result: list[dict] = []
    for item in changed_files:
        op = str(item.get("op", "")).lower()
        path = str(item.get("path", ""))
        if op == "delete":
            result.append(item)
            continue
        if should_skip_indexing_path(path):
            continue
        result.append(item)
    return result


def count_indexable_change_upserts(changed_files: list[dict]) -> int:
    total = 0
    for item in changed_files:
        op = str(item.get("op", "")).lower()
        if op == "delete":
            continue
        path = str(item.get("path", ""))
        if should_skip_indexing_path(path):
            continue
        total += 1
    return total


def _path_parts(path: str) -> tuple[str, ...]:
    normalized = (path or "").replace("\\", "/").strip()
    if not normalized:
        return ()
    posix = PurePosixPath(normalized)
    return tuple(part for part in posix.parts if part not in {"", "/"} and part != ".")


def _is_hidden_part(part: str) -> bool:
    return part not in {".", ".."} and part.startswith(".")
