"""
Clean command implementation.

Implements the 'precipgen clean' command for removing station data
with confirmation prompts and safety checks.
"""

import argparse
import sys
from typing import Optional

from precipgen.utils import get_logger
from precipgen.utils.directory_manager import DirectoryManager


def add_parser(subparsers) -> argparse.ArgumentParser:
    """
    Add clean command parser to subparsers.
    
    Args:
        subparsers: ArgumentParser subparsers object
        
    Returns:
        The clean command parser
    """
    parser = subparsers.add_parser(
        "clean",
        help="Remove station data with confirmation",
        description="Clean up station directories and files with safety prompts",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  precipgen clean --station USC00426128
  precipgen clean --station USC00426128 --force
  precipgen clean --all --output-dir /path/to/analysis
  precipgen clean --workflow simulation --station USC00426128
        """
    )
    
    # Target selection (mutually exclusive)
    target_group = parser.add_mutually_exclusive_group(required=True)
    target_group.add_argument(
        "--station", "-s",
        type=str,
        help="Station ID to clean"
    )
    target_group.add_argument(
        "--all",
        action="store_true",
        help="Clean all station directories (use with caution)"
    )
    
    # Scope options
    parser.add_argument(
        "--workflow", "-w",
        choices=["data", "analysis", "simulation", "validation"],
        help="Clean specific workflow only (keeps other workflows)"
    )
    
    # Safety options
    parser.add_argument(
        "--force", "-f",
        action="store_true",
        help="Skip confirmation prompts (dangerous)"
    )
    
    parser.add_argument(
        "--dry-run", "-n",
        action="store_true",
        help="Show what would be deleted without actually deleting"
    )
    
    # Output options
    parser.add_argument(
        "--output-dir", "-o",
        type=str,
        help="Custom output directory (default: ./precipgen_output)"
    )
    
    parser.add_argument(
        "--verbose", "-v",
        action="store_true",
        help="Show detailed information about files being deleted"
    )
    
    return parser


def format_file_size(size_mb: float) -> str:
    """
    Format file size in human-readable format.
    
    Args:
        size_mb: Size in megabytes
        
    Returns:
        Formatted size string
    """
    if size_mb < 1:
        return f"{size_mb * 1024:.1f} KB"
    elif size_mb < 1024:
        return f"{size_mb:.1f} MB"
    else:
        return f"{size_mb / 1024:.1f} GB"


def confirm_deletion(message: str, force: bool = False) -> bool:
    """
    Prompt user for deletion confirmation.
    
    Args:
        message: Confirmation message
        force: Skip confirmation if True
        
    Returns:
        True if user confirms deletion
    """
    if force:
        return True
    
    print(f"\n{message}")
    
    while True:
        try:
            response = input("Are you sure? (yes/no): ").strip().lower()
            
            if response in ['yes', 'y']:
                return True
            elif response in ['no', 'n']:
                return False
            else:
                print("Please enter 'yes' or 'no'")
                
        except KeyboardInterrupt:
            print("\nOperation cancelled")
            return False


def show_deletion_preview(station_info, workflow: Optional[str] = None, verbose: bool = False) -> None:
    """
    Show preview of what will be deleted.
    
    Args:
        station_info: StationDirectory object
        workflow: Specific workflow to clean (None for all)
        verbose: Show detailed file list
    """
    print(f"\nDeletion Preview for Station: {station_info.station_id}")
    print("-" * 50)
    
    if workflow:
        print(f"Workflow: {workflow.capitalize()}")
        
        if workflow == "data":
            files_to_delete = station_info.data_files
        elif workflow == "analysis":
            files_to_delete = station_info.analysis_files
        elif workflow == "simulation":
            files_to_delete = station_info.simulation_files
        elif workflow == "validation":
            files_to_delete = station_info.validation_files
        else:
            files_to_delete = []
        
        print(f"Files to delete: {len(files_to_delete)}")
        
        if verbose and files_to_delete:
            print("File list:")
            for file_path in files_to_delete:
                print(f"  • {file_path}")
    
    else:
        # Show all workflows
        total_files = (len(station_info.data_files) + len(station_info.analysis_files) + 
                      len(station_info.simulation_files) + len(station_info.validation_files))
        
        print(f"Directory: {station_info.directory_path}")
        print(f"Total size: {format_file_size(station_info.total_size_mb)}")
        print(f"Total files: {total_files}")
        print()
        
        print("Files by workflow:")
        print(f"  Data:       {len(station_info.data_files)} files")
        print(f"  Analysis:   {len(station_info.analysis_files)} files")
        print(f"  Simulation: {len(station_info.simulation_files)} files")
        print(f"  Validation: {len(station_info.validation_files)} files")
        
        if verbose:
            if station_info.data_files:
                print("\nData files:")
                for file_path in station_info.data_files:
                    print(f"  • {file_path}")
            
            if station_info.analysis_files:
                print("\nAnalysis files:")
                for file_path in station_info.analysis_files:
                    print(f"  • {file_path}")
            
            if station_info.simulation_files:
                print("\nSimulation files:")
                for file_path in station_info.simulation_files:
                    print(f"  • {file_path}")
            
            if station_info.validation_files:
                print("\nValidation files:")
                for file_path in station_info.validation_files:
                    print(f"  • {file_path}")


def clean_workflow_files(station_info, workflow: str, dry_run: bool = False, verbose: bool = False) -> bool:
    """
    Clean files for a specific workflow.
    
    Args:
        station_info: StationDirectory object
        workflow: Workflow to clean
        dry_run: Don't actually delete if True
        verbose: Show detailed progress
        
    Returns:
        True if successful
    """
    import shutil
    from pathlib import Path
    
    workflow_dir = station_info.directory_path / workflow
    
    if not workflow_dir.exists():
        if verbose:
            print(f"Workflow directory does not exist: {workflow_dir}")
        return True
    
    if dry_run:
        print(f"Would delete workflow directory: {workflow_dir}")
        return True
    
    try:
        shutil.rmtree(workflow_dir)
        if verbose:
            print(f"✓ Deleted workflow directory: {workflow_dir}")
        return True
        
    except Exception as e:
        print(f"✗ Failed to delete workflow directory {workflow_dir}: {e}")
        return False


def clean_station_directory(station_info, dry_run: bool = False, verbose: bool = False) -> bool:
    """
    Clean entire station directory.
    
    Args:
        station_info: StationDirectory object
        dry_run: Don't actually delete if True
        verbose: Show detailed progress
        
    Returns:
        True if successful
    """
    import shutil
    
    if dry_run:
        print(f"Would delete station directory: {station_info.directory_path}")
        return True
    
    try:
        shutil.rmtree(station_info.directory_path)
        if verbose:
            print(f"✓ Deleted station directory: {station_info.directory_path}")
        return True
        
    except Exception as e:
        print(f"✗ Failed to delete station directory {station_info.directory_path}: {e}")
        return False


def execute(args) -> int:
    """
    Execute the clean command.
    
    Args:
        args: Parsed command line arguments
        
    Returns:
        Exit code (0 for success, non-zero for error)
    """
    logger = get_logger("precipgen.cli.clean")
    
    try:
        # Initialize directory manager
        dir_manager = DirectoryManager(args.output_dir or "./precipgen_output")
        
        # Safety check for --all without --force
        if args.all and not args.force and not args.dry_run:
            print("WARNING: --all will delete ALL station directories!")
            print("Use --force to skip this warning or --dry-run to preview")
            
            if not confirm_deletion("This will delete ALL PrecipGen output data"):
                print("Operation cancelled")
                return 0
        
        # Get stations to clean
        stations_to_clean = []
        
        if args.station:
            # Clean specific station
            station_info = dir_manager.get_station_info(args.station, args.output_dir)
            if not station_info:
                print(f"Error: Station directory not found for {args.station}")
                return 1
            stations_to_clean = [station_info]
            
        elif args.all:
            # Clean all stations
            stations_to_clean = dir_manager.list_station_directories(args.output_dir)
            
            if not stations_to_clean:
                print("No station directories found to clean")
                return 0
        
        # Process each station
        success_count = 0
        error_count = 0
        
        for station_info in stations_to_clean:
            
            # Show preview
            if args.verbose or args.dry_run:
                show_deletion_preview(station_info, args.workflow, args.verbose)
            
            # Confirm deletion for individual stations (unless --force or --all)
            if not args.force and not args.all and not args.dry_run:
                if args.workflow:
                    message = f"Delete {args.workflow} workflow for station {station_info.station_id}?"
                else:
                    message = f"Delete all data for station {station_info.station_id}?"
                
                if not confirm_deletion(message):
                    print(f"Skipped station {station_info.station_id}")
                    continue
            
            # Perform deletion
            if args.workflow:
                # Clean specific workflow
                success = clean_workflow_files(station_info, args.workflow, args.dry_run, args.verbose)
            else:
                # Clean entire station
                success = clean_station_directory(station_info, args.dry_run, args.verbose)
            
            if success:
                success_count += 1
                if not args.dry_run:
                    if args.workflow:
                        print(f"✓ Cleaned {args.workflow} workflow for station {station_info.station_id}")
                    else:
                        print(f"✓ Cleaned station {station_info.station_id}")
            else:
                error_count += 1
        
        # Summary
        if args.dry_run:
            print(f"\nDry run completed: {len(stations_to_clean)} stations would be processed")
        else:
            print(f"\nCleanup completed: {success_count} successful, {error_count} errors")
            
            if success_count > 0:
                if args.workflow:
                    print(f"Cleaned {args.workflow} workflow for {success_count} stations")
                else:
                    print(f"Cleaned {success_count} station directories")
        
        return 0 if error_count == 0 else 1
        
    except KeyboardInterrupt:
        print("\nOperation cancelled by user")
        return 130
    except Exception as e:
        logger.error(f"Unexpected error in clean command: {e}")
        print(f"Error: {e}")
        return 1