#!/usr/bin/env python3
"""
dupeSweep - Find and remove duplicate files safely with undo capability.

Usage:
    dupesweep                  # Launch GUI (no args)
    dupesweep scan <path>      # Scan directory
    dupesweep remove <paths>   # Remove files
    dupesweep undo             # Undo last operation
    dupesweep status           # Show recent operations
    dupesweep help             # Show help
"""
import sys
import os
from pathlib import Path

# Allow running as module or script
if __name__ == "__main__":
    # Add parent directory to path for imports
    sys.path.insert(0, str(Path(__file__).parent))
    main()


def main():
    """Main entry point for dupeSweep."""
    args = sys.argv[1:]

    # No arguments - launch GUI
    if not args:
        from ui.gui import run_gui
        run_gui()
        return
    
    # CLI commands
    command = args[0]
    
    if command == "scan":
        cmd_scan(args[1:])
    elif command == "remove":
        cmd_remove(args[1:])
    elif command == "undo":
        cmd_undo()
    elif command == "status":
        cmd_status()
    elif command == "help" or command == "--help" or command == "-h":
        print_help()
    else:
        print(f"Unknown command: {command}")
        print("Run 'dedup help' for usage information.")
        sys.exit(1)


def cmd_scan(args):
    """Scan directory for duplicates."""
    from core.scanner import FileScanner
    from ui.cli_output import print_table, print_stats
    import sys
    
    if not args:
        print("Usage: dedup scan <path>")
        sys.exit(1)
    
    path = args[0]
    
    if not os.path.isdir(path):
        print(f"Error: '{path}' is not a valid directory")
        sys.exit(1)
    
    print(f"Scanning: {path}")
    print("-" * 50)
    
    scanner = FileScanner(progress_callback=lambda p, c, t: (print(f"\rProgress: {c}/{t}", end=""), sys.stdout.flush()))
    duplicates = scanner.scan_directory(path)
    stats = scanner.get_statistics()
    
    print("\n")
    print_stats(stats)
    
    if duplicates:
        print(f"\nFound {len(duplicates)} duplicate groups\n")
        print_table(duplicates)
    else:
        print("\nNo duplicates found!")


def cmd_remove(args):
    """Remove specified files."""
    from actions.file_ops import FileManager, UndoManager
    
    if not args:
        print("Usage: dedup remove <file1> [file2] ...")
        sys.exit(1)
    
    # Validate all paths first
    valid_files = []
    for filepath in args:
        if os.path.isfile(filepath):
            valid_files.append(filepath)
        else:
            print(f"Error: File not found: {filepath}", file=sys.stderr)
    
    if not valid_files:
        print("No valid files to remove.", file=sys.stderr)
        sys.exit(1)
    
    undo_manager = UndoManager()
    file_manager = FileManager(undo_manager=undo_manager)
    batch_id = file_manager.start_batch(f"CLI removal of {len(valid_files)} file(s)")
    
    for filepath in valid_files:
        file_manager.delete_file(filepath)
    
    for msg in file_manager.get_messages():
        print(msg)
    
    print(f"\nBatch ID: {batch_id}")
    print("Use 'dedup undo' to restore files.")


def cmd_undo():
    """Undo last operation."""
    from actions.file_ops import UndoManager
    
    undo_manager = UndoManager()
    batches = undo_manager.get_recent_batches()
    
    if not batches:
        print("No operations to undo.")
        return
    
    last_batch = batches[0]
    print(f"Undoing: {last_batch.description}")
    print(f"Operations: {len(last_batch.operations)}")
    
    success, messages = undo_manager.undo_batch(last_batch.batch_id)
    
    for msg in messages:
        print(msg)
    
    if success:
        print("\nUndo complete!")
    else:
        print("\nUndo completed with errors.")


def cmd_status():
    """Show recent operations."""
    from actions.file_ops import UndoManager
    
    undo_manager = UndoManager()
    batches = undo_manager.get_recent_batches(10)
    
    if not batches:
        print("No recent operations.")
        return
    
    print("Recent Operations:")
    print("-" * 60)
    
    for batch in batches:
        from datetime import datetime
        dt = datetime.fromtimestamp(batch.timestamp)
        print(f"\n{batch.batch_id}")
        print(f"  Time: {dt.strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"  Description: {batch.description}")
        print(f"  Operations: {len(batch.operations)}")


def print_help():
    """Print help information."""
    help_text = """
File Deduplicator - Find and remove duplicate files safely

USAGE:
    dedup [COMMAND] [OPTIONS]

COMMANDS:
    (no args)     Launch graphical interface
    scan <path>   Scan directory for duplicates
    remove <files> Remove specified files (with undo support)
    undo          Undo last batch operation
    status        Show recent operations
    help          Show this help message

EXAMPLES:
    dedup                     # Open GUI
    dedup scan ~/Downloads    # Scan Downloads folder
    dedup status              # Check recent operations
    dedup undo                # Restore last batch

For more information, see the documentation.
"""
    print(help_text)


if __name__ == "__main__":
    main()
