"""File scanner implementation"""

import os
import threading
from typing import List

from .queue import ThreadSafeQueue
from .constants import MAX_FILES


class FileScanner:
    """File scanner class"""
    
    def __init__(self, directories: List[str], queue: ThreadSafeQueue):
        """Initialize file scanner
        
        Args:
            directories: Directories to scan
            queue: Thread-safe queue to store file paths
        """
        self.directories = directories
        self.queue = queue
        self.file_count = 0
        self.lock = threading.Lock()
    
    def scan_directory(self, directory: str):
        """Scan a directory for files using recursive os.walk
        
        Args:
            directory: Directory to scan
        """
        if not os.path.exists(directory) or not os.path.isdir(directory):
            return
        
        try:
            # Use os.walk to recursively scan directory
            for root, dirs, files in os.walk(directory):
                # Check if we've reached the maximum file count
                with self.lock:
                    if self.file_count >= MAX_FILES:
                        return
                
                for file in files:
                    # Check if we've reached the maximum file count
                    with self.lock:
                        if self.file_count >= MAX_FILES:
                            return
                    
                    # Construct full file path
                    file_path = os.path.join(root, file)
                    
                    # Check if it's a file (not a directory)
                    if os.path.isfile(file_path):
                        with self.lock:
                            if self.file_count < MAX_FILES:
                                self.queue.put(file_path)
                                self.file_count += 1
                            else:
                                return
        except Exception as e:
            # Ignore errors (e.g., access denied)
            pass
    
    def start_scanning(self):
        """Start scanning directories in threads"""
        threads = []
        
        # Create a thread for each directory
        for directory in self.directories:
            thread = threading.Thread(
                target=self.scan_directory,
                args=(directory,),
                daemon=True  # Set as daemon thread
            )
            threads.append(thread)
            thread.start()
        
        # Wait for all threads to complete or be interrupted
        try:
            for thread in threads:
                thread.join()
        except KeyboardInterrupt:
            # Handle Ctrl+C gracefully
            pass
        
        # Stop the queue
        self.queue.stop()
