"""
Command-line interface for file time modification tool
"""

import argparse
import sys
import os
from pathlib import Path

# Add parent directory to path for imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))

from diona.tools.program.file_time_modifier import FileTimeModifier


def create_parser():
    """Create command-line argument parser"""
    parser = argparse.ArgumentParser(
        description="Modify file creation and modification times",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Add 1 day to all files in current directory
  file_time_modify . -d 1
  
  # Subtract 2 hours from all .txt files recursively
  file_time_modify /path/to/dir -H 2 -o subtract -r -p "*.txt"
  
  # Add 1 year and 3 months to files
  file_time_modify /path/to/dir -y 1 -m 3
  
  # Dry run to see what would be modified
  file_time_modify /path/to/dir -d 7 --dry-run
        """
    )
    
    parser.add_argument(
        "directory",
        help="Target directory path"
    )
    
    parser.add_argument(
        "-y", "--years",
        type=int,
        default=0,
        help="Years to add/subtract (default: 0)"
    )
    
    parser.add_argument(
        "-m", "--months",
        type=int,
        default=0,
        help="Months to add/subtract (default: 0)"
    )
    
    parser.add_argument(
        "-d", "--days",
        type=int,
        default=0,
        help="Days to add/subtract (default: 0)"
    )
    
    parser.add_argument(
        "-H", "--hours",
        type=int,
        default=0,
        help="Hours to add/subtract (default: 0)"
    )
    
    parser.add_argument(
        "-o", "--operation",
        choices=["add", "subtract"],
        default="add",
        help="Operation: add or subtract (default: add)"
    )
    
    parser.add_argument(
        "-r", "--recursive",
        action="store_true",
        help="Process subdirectories recursively"
    )
    
    parser.add_argument(
        "-p", "--pattern",
        help="File pattern to match (e.g., *.txt, *.py)"
    )
    
    parser.add_argument(
        "--dry-run",
        action="store_true",
        help="Show what would be modified without making changes"
    )
    
    parser.add_argument(
        "-v", "--verbose",
        action="store_true",
        help="Show verbose output"
    )
    
    return parser


def main(args=None):
    """Main command-line entry point"""
    parser = create_parser()
    
    if args is None:
        args = sys.argv[1:]
    
    parsed_args = parser.parse_args(args)
    
    # Create modifier instance
    modifier = FileTimeModifier()
    
    try:
        if parsed_args.dry_run:
            print("DRY RUN - No changes will be made")
            print(f"Directory: {parsed_args.directory}")
            print(f"Operation: {parsed_args.operation}")
            print(f"Time delta: {parsed_args.years}y {parsed_args.months}m {parsed_args.days}d {parsed_args.hours}h")
            print(f"Recursive: {parsed_args.recursive}")
            print(f"Pattern: {parsed_args.pattern}")
            
            # Simulate file listing
            path = Path(parsed_args.directory)
            if parsed_args.pattern:
                if parsed_args.recursive:
                    files = list(path.rglob(parsed_args.pattern))
                else:
                    files = list(path.glob(parsed_args.pattern))
            else:
                if parsed_args.recursive:
                    files = list(path.rglob("*"))
                else:
                    files = list(path.glob("*"))
            
            files = [f for f in files if f.is_file()]
            
            print(f"\nFiles that would be modified ({len(files)}):")
            for file_path in files[:10]:  # Show first 10 files
                print(f"  {file_path}")
            
            if len(files) > 10:
                print(f"  ... and {len(files) - 10} more files")
            
            return 0
        
        # Modify file times
        modified_files = modifier.modify_file_times(
            directory=parsed_args.directory,
            years=parsed_args.years,
            months=parsed_args.months,
            days=parsed_args.days,
            hours=parsed_args.hours,
            operation=parsed_args.operation,
            recursive=parsed_args.recursive,
            file_pattern=parsed_args.pattern
        )
        
        # Print summary
        summary = modifier.get_summary()
        
        print(f"\n{'='*50}")
        print("FILE TIME MODIFICATION SUMMARY")
        print(f"{'='*50}")
        print(f"Directory: {parsed_args.directory}")
        print(f"Operation: {parsed_args.operation}")
        print(f"Time delta: {parsed_args.years}y {parsed_args.months}m {parsed_args.days}d {parsed_args.hours}h")
        print(f"Recursive: {parsed_args.recursive}")
        print(f"Pattern: {parsed_args.pattern or '* (all files)'}")
        print(f"Files modified: {summary['total_files_modified']}")
        print(f"{'='*50}")
        
        if parsed_args.verbose and modified_files:
            print("\nModified files:")
            for file_path in modified_files:
                print(f"  {file_path}")
        
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        return 1
    
    return 0


if __name__ == "__main__":
    sys.exit(main())