"""Scanning functionality for electron-angle-patcher."""

from __future__ import annotations

import logging
import os
from pathlib import Path

from electron_angle_patcher.config import Config
from electron_angle_patcher.models import AppInfo
from electron_angle_patcher.utils import extract_app_name, get_network_mounts

logger = logging.getLogger(__name__)


class LocalStateScanner:
    """Scanner for finding Chromium/Electron Local State files."""

    def __init__(self, skip_patterns: frozenset[str] = frozenset()) -> None:
        """Initialize the scanner.

        Args:
            skip_patterns: Patterns to skip when scanning.
        """
        self._skip_patterns = skip_patterns
        self._network_mounts: set[Path] | None = None

    def _should_skip_directory(
        self,
        root: Path,
        dirname: str,
    ) -> bool:
        """Determine if a directory should be skipped during scanning.

        Args:
            root: Root directory path.
            dirname: Directory name to check.

        Returns:
            True if directory should be skipped, False otherwise.
        """
        full_path = root / dirname

        # Skip hidden directories
        if dirname.startswith('.'):
            return True

        # Skip known directories
        if any(skip_path in str(full_path) for skip_path in Config.SKIP_DIRS):
            return True

        # Skip network mounts
        return bool(
            self._network_mounts
            and any(
                str(full_path).startswith(str(mount))
                for mount in self._network_mounts
            )
        )

    def scan(self, start_dir: Path) -> list[AppInfo]:
        """Walk through directories to find all Local State files.

        Args:
            start_dir: Root directory to start scanning from.

        Returns:
            List of AppInfo objects for discovered apps.
        """
        start_dir = start_dir.expanduser()
        results = []

        # Cache network mounts for performance
        if self._network_mounts is None:
            self._network_mounts = get_network_mounts()

        for root, dirs, files in os.walk(start_dir):
            # Prune directories in-place
            dirs[:] = [
                d for d in dirs
                if not self._should_skip_directory(Path(root), d)
            ]

            if "Local State" in files:
                state_file = Path(root) / "Local State"
                app_name = extract_app_name(state_file, start_dir)

                # Apply skip patterns
                if not any(
                    pattern in state_file.as_posix().lower()
                    for pattern in self._skip_patterns
                ):
                    results.append(AppInfo(name=app_name, state_file=state_file))

        return results
