#!/usr/bin/env python3
"""
rfind - Python scanner implementation
"""

import os
import itertools
import multiprocessing
from typing import List, Tuple

def scan_directory(path: str = ".", 
                   chars: str = "abcdefghijklmnopqrstuvwxyz",
                   min_len: int = 1, 
                   max_len: int = 3,
                   threads: int = 1) -> List[Tuple[str, str]]:
    """
    Brute-force directory scanning
    
    Args:
        path: Target directory
        chars: Characters to use for filename generation
        min_len: Minimum filename length
        max_len: Maximum filename length
        threads: Number of threads to use
    
    Returns:
        List of (filename, type) tuples where type is 'file' or 'dir'
    """
    results = []
    
    for length in range(min_len, max_len + 1):
        for combo in itertools.product(chars, repeat=length):
            filename = ''.join(combo)
            full_path = os.path.join(path, filename)
            
            if os.path.exists(full_path):
                if os.path.isdir(full_path):
                    results.append((filename, 'dir'))
                else:
                    results.append((filename, 'file'))
    
    return results

def smart_scan(path: str = ".",
               chars: str = "abcdefghijklmnopqrstuvwxyz",
               min_len: int = 1,
               max_len: int = 3) -> List[Tuple[str, str]]:
    """
    Smart scanning using common patterns
    
    Args:
        path: Target directory
        chars: Allowed characters
        min_len: Minimum filename length
        max_len: Maximum filename length
    
    Returns:
        List of (filename, type) tuples
    """
    results = []
    
    # Common patterns for Unix/Linux/Android systems
    common_patterns = [
        # Single character
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
        'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
        
        # Two characters
        'sh', 'ls', 'cp', 'mv', 'rm', 'cd', 'ps', 'df', 'du', 'wc', 'vi',
        'cc', 'as', 'ld', 'ar', 'nm', 'od', 'dc', 'bc', 'ex', 'ed',
        
        # Three characters
        'bin', 'dev', 'etc', 'lib', 'tmp', 'usr', 'var', 'sys', 'proc',
        'mnt', 'opt', 'srv', 'run', 'home', 'root', 'boot', 'media',
        'sbin', 'etc', 'opt', 'var', 'tmp', 'usr', 'lib', 'bin',
        
        # Common files
        '.', '..', '.git', '.bashrc', '.profile', '.config', '.local',
        'Makefile', 'README', 'LICENSE', 'Dockerfile', '.env',
        
        # Android specific
        'init', 'system', 'vendor', 'product', 'odm', 'oem', 'data',
        'cache', 'metadata', 'acct', 'apex', 'config', 'd',
        'debug_ramdisk', 'efs', 'firmware', 'keydata',
    ]
    
    for pattern in common_patterns:
        pattern_len = len(pattern)
        
        # Check length constraints
        if pattern_len < min_len or pattern_len > max_len:
            continue
        
        # Check character constraints
        valid = True
        for char in pattern:
            if char not in chars and char != '.' and char != '_' and char != '-':
                valid = False
                break
        
        if not valid:
            continue
        
        full_path = os.path.join(path, pattern)
        
        if os.path.exists(full_path):
            if os.path.isdir(full_path):
                results.append((pattern, 'dir'))
            else:
                results.append((pattern, 'file'))
    
    return results

def parallel_scan(path: str = ".",
                  chars: str = "abcdefghijklmnopqrstuvwxyz",
                  min_len: int = 1,
                  max_len: int = 3,
                  threads: int = None) -> List[Tuple[str, str]]:
    """
    Parallel brute-force scanning using multiprocessing
    
    Args:
        path: Target directory
        chars: Characters to use
        min_len: Minimum length
        max_len: Maximum length
        threads: Number of processes (default: CPU count)
    
    Returns:
        List of (filename, type) tuples
    """
    if threads is None:
        threads = multiprocessing.cpu_count()
    
    if threads <= 1:
        return scan_directory(path, chars, min_len, max_len, 1)
    
    # Split work by starting characters
    results = []
    
    def worker(start_char):
        worker_results = []
        for length in range(min_len, max_len + 1):
            # Generate combinations starting with start_char
            if length == 1:
                filename = start_char
                full_path = os.path.join(path, filename)
                if os.path.exists(full_path):
                    worker_results.append((filename, 
                                          'dir' if os.path.isdir(full_path) else 'file'))
            else:
                # Need to generate all combinations for longer lengths
                pass
        return worker_results
    
    # This is a simplified version - full implementation would need
    # proper work distribution
    return scan_directory(path, chars, min_len, max_len, 1)

if __name__ == "__main__":
    # Test the scanner
    print("Testing scanner...")
    
    # Test smart scan
    results = smart_scan(".", min_len=1, max_len=4)
    print(f"Smart scan found {len(results)} items:")
    for name, ftype in sorted(results)[:10]:  # Show first 10
        print(f"  {ftype.upper()}: {name}")
    
    if len(results) > 10:
        print(f"  ... and {len(results) - 10} more")
