"""
Quick Sensitive File Search Tool
Provides simple function interface and command line tool for quick progressive sensitive file search
"""

import os
import sys
import json
import argparse
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Optional, Any

from .progressive_search import ProgressiveSearch, SearchConfig
from .models import SearchStatus


class QuickSearch:
    """Quick sensitive file search tool class"""
    
    def __init__(self):
        """Initialize search engine"""
        self.search_engine = ProgressiveSearch()
    
    def create_search_config(
        self,
        target_directory: str,
        max_files_per_session: int = 1000,
        max_depth: int = 5,
        min_file_size: int = 0,
        max_file_size: int = 100 * 1024 * 1024,  # 100MB
        include_hidden_files: bool = True
    ) -> SearchConfig:
        """
        Create search configuration
        
        Args:
            target_directory: Target search directory
            max_files_per_session: Maximum files per session
            max_depth: Maximum search depth
            min_file_size: Minimum file size (bytes)
            max_file_size: Maximum file size (bytes)
            include_hidden_files: Include hidden files
            
        Returns:
            SearchConfig: Search configuration object
        """
        return SearchConfig(
            target_directory=target_directory,
            max_files_per_session=max_files_per_session,
            max_depth=max_depth,
            min_file_size=min_file_size,
            max_file_size=max_file_size,
            include_hidden_files=include_hidden_files
        )
    
    def progressive_search(
        self,
        task_name: str,
        target_directory: str,
        max_files_per_session: int = 1000,
        max_depth: int = 5,
        results_file: str = None,
        auto_complete: bool = False
    ) -> Dict[str, Any]:
        """
        Execute progressive sensitive file search
        
        Args:
            task_name: Task name for identifying search session
            target_directory: Target search directory
            max_files_per_session: Maximum files per session
            max_depth: Maximum search depth
            results_file: Results file path, defaults to {task_name}_results.json
            auto_complete: Auto-complete entire search (multiple sessions until done)
            
        Returns:
            Dict[str, Any]: Search result statistics
        """
        # Set default results file
        if results_file is None:
            results_file = f"{task_name}_results.json"
        
        # Create search configuration
        config = self.create_search_config(
            target_directory=target_directory,
            max_files_per_session=max_files_per_session,
            max_depth=max_depth
        )
        
        # Create or load search session
        session_id = self.search_engine.create_search_session(config, task_name)
        
        print(f"🚀 Starting progressive sensitive file search")
        print(f"   Task name: {task_name}")
        print(f"   Target directory: {target_directory}")
        print(f"   Max depth: {max_depth}")
        print(f"   Files per session: {max_files_per_session}")
        print(f"   Results file: {results_file}")
        print()
        
        session_count = 0
        
        # Execute search sessions
        while True:
            session_count += 1
            
            # Get current progress
            progress = self.search_engine.get_search_progress(session_id)
            
            print(f"📊 Search session {session_count}")
            print(f"   Progress: {progress.get('progress_percentage', 0):.1f}%")
            print(f"   Files scanned: {progress.get('total_files_scanned', 0)}")
            print(f"   Sensitive files found: {progress.get('files_found', 0)}")
            print(f"   Pending directories: {progress.get('pending_directories', 0)}")
            
            # Execute search session
            search_state = self.search_engine.execute_search_session(session_id)
            
            # Check search status
            if search_state.status == SearchStatus.COMPLETED:
                print("✅ Search completed!")
                break
            elif search_state.status == SearchStatus.PAUSED:
                print("⏸️  Search paused, ready for next session")
                
                # If not auto-complete mode, ask user to continue
                if not auto_complete:
                    response = input("Continue to next search session? (y/n): ").lower().strip()
                    if response not in ['y', 'yes']:
                        print("⏹️  User terminated search")
                        break
            
            print()
        
        # Get final results
        results = self.search_engine.get_search_results(session_id)
        
        # Save results to file
        self.search_engine.save_search_results(session_id, results_file)
        
        # Copy results file to current directory
        self._copy_results_to_current_dir(session_id, results_file)
        
        # Generate statistics
        stats = self._generate_statistics(search_state, results)
        
        print("\n" + "="*60)
        print("📈 Search Statistics")
        print("="*60)
        print(f"Total files scanned: {stats['total_files_scanned']}")
        print(f"Total sensitive files found: {stats['total_files_found']}")
        print(f"Total directories scanned: {stats['total_directories_scanned']}")
        print(f"Search duration: {stats['search_duration']}")
        print(f"Results file: {results_file}")
        
        # Display sensitive file type distribution
        if stats['file_type_distribution']:
            print("\n📊 Sensitive File Type Distribution:")
            for file_type, count in stats['file_type_distribution'].items():
                print(f"   {file_type}: {count} files")
        
        return stats
    
    def _copy_results_to_current_dir(self, session_id: str, results_file: str):
        """Copy results file to current directory"""
        import shutil
        
        # Get results file path in storage directory
        storage_path = self.search_engine.storage.get_path(
            self.search_engine.search_module,
            f"{self.search_engine.search_dir}/{results_file}",
            "project"
        )
        
        # Target path (current directory)
        current_dir_path = os.path.join(os.getcwd(), results_file)
        
        # If results file exists in storage directory, copy to current directory
        if os.path.exists(storage_path):
            shutil.copy2(storage_path, current_dir_path)
            print(f"📄 Results file saved to: {current_dir_path}")
        else:
            print(f"⚠️  Results file not found: {storage_path}")
    
    def _generate_statistics(self, search_state, results: List) -> Dict[str, Any]:
        """Generate search statistics"""
        
        # Calculate search duration
        if search_state.start_time and search_state.end_time:
            duration = search_state.end_time - search_state.start_time
            duration_str = f"{duration.total_seconds():.1f} seconds"
        else:
            duration_str = "unknown"
        
        # Count file type distribution
        file_type_distribution = {}
        for result in results:
            file_type = result.file_type
            file_type_distribution[file_type] = file_type_distribution.get(file_type, 0) + 1
        
        return {
            "total_files_scanned": search_state.total_files_scanned,
            "total_files_found": len(results),
            "total_directories_scanned": search_state.total_directories_scanned,
            "search_duration": duration_str,
            "file_type_distribution": file_type_distribution,
            "session_id": search_state.session_id,
            "task_name": search_state.task_name
        }
    
    def resume_search(
        self,
        task_name: str,
        results_file: str = None,
        auto_complete: bool = False
    ) -> Dict[str, Any]:
        """
        Resume previous search task
        
        Args:
            task_name: Task name
            results_file: Results file path
            auto_complete: Auto-complete entire search
            
        Returns:
            Dict[str, Any]: Search result statistics
        """
        # Set default results file
        if results_file is None:
            results_file = f"{task_name}_results.json"
        
        # Find corresponding session ID
        sessions = self.search_engine.list_search_sessions()
        session_id = None
        
        for session in sessions:
            if session.get("task_name") == task_name:
                session_id = session.get("session_id")
                break
        
        if not session_id:
            raise ValueError(f"Search session for task '{task_name}' not found")
        
        print(f"🔄 Resuming search task: {task_name}")
        
        # Continue search execution
        return self._continue_search(session_id, results_file, auto_complete)
    
    def _continue_search(
        self,
        session_id: str,
        results_file: str,
        auto_complete: bool
    ) -> Dict[str, Any]:
        """Continue search session execution"""
        
        session_count = 0
        
        # Execute search sessions
        while True:
            session_count += 1
            
            # Get current progress
            progress = self.search_engine.get_search_progress(session_id)
            
            print(f"📊 Search session {session_count} (resumed)")
            print(f"   Progress: {progress.get('progress_percentage', 0):.1f}%")
            print(f"   Files scanned: {progress.get('total_files_scanned', 0)}")
            print(f"   Sensitive files found: {progress.get('files_found', 0)}")
            
            # Execute search session
            search_state = self.search_engine.execute_search_session(session_id)
            
            # Check search status
            if search_state.status == SearchStatus.COMPLETED:
                print("✅ Search completed!")
                break
            elif search_state.status == SearchStatus.PAUSED:
                print("⏸️  Search paused, ready for next session")
                
                # If not auto-complete mode, ask user to continue
                if not auto_complete:
                    response = input("Continue to next search session? (y/n): ").lower().strip()
                    if response not in ['y', 'yes']:
                        print("⏹️  User terminated search")
                        break
            
            print()
        
        # Get final results
        results = self.search_engine.get_search_results(session_id)
        
        # Save results to file
        self.search_engine.save_search_results(session_id, results_file)
        
        # Generate statistics
        stats = self._generate_statistics(search_state, results)
        
        print("\n" + "="*60)
        print("📈 Search Statistics")
        print("="*60)
        print(f"Total files scanned: {stats['total_files_scanned']}")
        print(f"Total sensitive files found: {stats['total_files_found']}")
        print(f"Search duration: {stats['search_duration']}")
        print(f"Results file: {results_file}")
        
        return stats


def quick_search(
    task_name: str,
    target_directory: str,
    max_files_per_session: int = 1000,
    max_depth: int = 5,
    results_file: str = None,
    auto_complete: bool = False
) -> Dict[str, Any]:
    """
    Quick sensitive file search function
    
    Args:
        task_name: Task name
        target_directory: Target search directory
        max_files_per_session: Maximum files per session
        max_depth: Maximum search depth
        results_file: Results file path
        auto_complete: Auto-complete entire search
        
    Returns:
        Dict[str, Any]: Search result statistics
    """
    searcher = QuickSearch()
    return searcher.progressive_search(
        task_name=task_name,
        target_directory=target_directory,
        max_files_per_session=max_files_per_session,
        max_depth=max_depth,
        results_file=results_file,
        auto_complete=auto_complete
    )


def main():
    """Command line tool main function"""
    parser = argparse.ArgumentParser(
        description="Progressive Sensitive File Search Tool",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Usage Examples:
  # Basic search
  python quick_search.py --task my_search --target /path/to/search
  
  # Custom parameters search
  python quick_search.py --task my_search --target /path/to/search --max-files 500 --max-depth 3
  
  # Auto-complete search
  python quick_search.py --task my_search --target /path/to/search --auto-complete
  
  # Resume search task
  python quick_search.py --task my_search --resume
        """
    )
    
    parser.add_argument(
        "--task", "-t",
        required=True,
        help="Search task name"
    )
    
    parser.add_argument(
        "--target", "-d",
        help="Target search directory path"
    )
    
    parser.add_argument(
        "--resume", "-r",
        action="store_true",
        help="Resume previous search task"
    )
    
    parser.add_argument(
        "--max-files", "-f",
        type=int,
        default=1000,
        help="Maximum files per session (default: 1000)"
    )
    
    parser.add_argument(
        "--max-depth", "-l",
        type=int,
        default=5,
        help="Maximum search depth (default: 5)"
    )
    
    parser.add_argument(
        "--results-file", "-o",
        help="Results file path (default: {task_name}_results.json)"
    )
    
    parser.add_argument(
        "--auto-complete", "-a",
        action="store_true",
        help="Auto-complete entire search (no user confirmation)"
    )
    
    args = parser.parse_args()
    
    # Validate parameters
    if not args.resume and not args.target:
        parser.error("Must specify --target parameter or use --resume parameter")
    
    searcher = QuickSearch()
    
    try:
        if args.resume:
            # Resume search task
            stats = searcher.resume_search(
                task_name=args.task,
                results_file=args.results_file,
                auto_complete=args.auto_complete
            )
        else:
            # Start new search task
            stats = searcher.progressive_search(
                task_name=args.task,
                target_directory=args.target,
                max_files_per_session=args.max_files,
                max_depth=args.max_depth,
                results_file=args.results_file,
                auto_complete=args.auto_complete
            )
        
        # Return exit code
        sys.exit(0)
        
    except Exception as e:
        print(f"❌ Error: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()