"""
File Time Modification Tool
"""

import os
import argparse
from datetime import datetime, timedelta
from pathlib import Path
from typing import Optional, List


class FileTimeModifier:
    """
    File time modification utility for adjusting file creation and modification times
    """
    
    def __init__(self):
        self.modified_files = []
    
    def modify_file_times(
        self,
        directory: str,
        years: int = 0,
        months: int = 0,
        days: int = 0,
        hours: int = 0,
        operation: str = "add",
        recursive: bool = False,
        file_pattern: Optional[str] = None
    ) -> List[str]:
        """
        Modify creation and modification times of files in a directory
        
        Args:
            directory: Target directory path
            years: Number of years to add/subtract
            months: Number of months to add/subtract
            days: Number of days to add/subtract
            hours: Number of hours to add/subtract
            operation: "add" or "subtract"
            recursive: Whether to process subdirectories recursively
            file_pattern: File pattern to match (e.g., "*.txt")
            
        Returns:
            List of modified file paths
        """
        self.modified_files = []
        
        if not os.path.exists(directory):
            raise FileNotFoundError(f"Directory not found: {directory}")
        
        if not os.path.isdir(directory):
            raise ValueError(f"Path is not a directory: {directory}")
        
        # Calculate time delta
        time_delta = self._calculate_time_delta(years, months, days, hours, operation)
        
        # Process files
        self._process_directory(directory, time_delta, recursive, file_pattern)
        
        return self.modified_files
    
    def _calculate_time_delta(
        self,
        years: int,
        months: int,
        days: int,
        hours: int,
        operation: str
    ) -> timedelta:
        """
        Calculate time delta based on input parameters
        
        Args:
            years: Number of years
            months: Number of months
            days: Number of days
            hours: Number of hours
            operation: "add" or "subtract"
            
        Returns:
            Time delta object
        """
        # Convert years and months to days (approximate)
        total_days = days + (years * 365) + (months * 30)
        total_hours = hours
        
        if operation == "subtract":
            total_days = -total_days
            total_hours = -total_hours
        
        return timedelta(days=total_days, hours=total_hours)
    
    def _process_directory(
        self,
        directory: str,
        time_delta: timedelta,
        recursive: bool,
        file_pattern: Optional[str]
    ):
        """
        Process files and directories
        
        Args:
            directory: Directory path
            time_delta: Time delta to apply
            recursive: Whether to process subdirectories
            file_pattern: File pattern to match
        """
        path = Path(directory)
        
        # First, modify the directory itself
        self._modify_directory_time(path, time_delta)
        
        # Get file iterator based on pattern and recursion
        if file_pattern:
            if recursive:
                file_iterator = path.rglob(file_pattern)
            else:
                file_iterator = path.glob(file_pattern)
        else:
            if recursive:
                file_iterator = path.rglob("*")
            else:
                file_iterator = path.glob("*")
        
        for item_path in file_iterator:
            if item_path.is_file():
                self._modify_file_time(item_path, time_delta)
                pass
            elif item_path.is_dir():
                # Process subdirectories if recursive is enabled
                if recursive:
                    self._modify_directory_time(item_path, time_delta)
    
    def _modify_file_time(self, file_path: Path, time_delta: timedelta):
        """
        Modify file creation and modification times
        
        Args:
            file_path: Path to the file
            time_delta: Time delta to apply
        """
        try:
            # Get current file times
            stat_info = os.stat(file_path)
            creation_time = datetime.fromtimestamp(stat_info.st_ctime)
            modification_time = datetime.fromtimestamp(stat_info.st_mtime)
            
            # Calculate new times
            new_creation_time = creation_time + time_delta
            new_modification_time = modification_time + time_delta
            
            # Convert to timestamps
            creation_timestamp = new_creation_time.timestamp()
            modification_timestamp = new_modification_time.timestamp()
            
            # Modify file times (Windows-specific using os.utime)
            os.utime(file_path, (modification_timestamp, modification_timestamp))
            
            # Note: On Windows, creation time cannot be modified with standard Python
            # This will only modify the modification time
            # For creation time modification, additional Windows API calls would be needed
            
            self.modified_files.append(str(file_path))
            
            print(f"Modified: {file_path}")
            print(f"  Original creation: {creation_time}")
            print(f"  New creation: {new_creation_time}")
            print(f"  Original modification: {modification_time}")
            print(f"  New modification: {new_modification_time}")
            
        except Exception as e:
            print(f"Error modifying {file_path}: {e}")
    
    def _modify_directory_time(self, dir_path: Path, time_delta: timedelta):
        """
        Modify directory creation and modification times
        
        Args:
            dir_path: Path to the directory
            time_delta: Time delta to apply
        """
        try:
            # Get current directory times
            stat_info = os.stat(dir_path)
            creation_time = datetime.fromtimestamp(stat_info.st_ctime)
            modification_time = datetime.fromtimestamp(stat_info.st_mtime)
            
            # Calculate new times
            new_creation_time = creation_time + time_delta
            new_modification_time = modification_time + time_delta
            
            # Convert to timestamps
            creation_timestamp = new_creation_time.timestamp()
            modification_timestamp = new_modification_time.timestamp()
            
            # Modify directory times
            os.utime(dir_path, (modification_timestamp, modification_timestamp))
            
            # Note: On Windows, creation time cannot be modified with standard Python
            # This will only modify the modification time
            
            self.modified_files.append(str(dir_path))
            
            print(f"Modified directory: {dir_path}")
            print(f"  Original creation: {creation_time}")
            print(f"  New creation: {new_creation_time}")
            print(f"  Original modification: {modification_time}")
            print(f"  New modification: {new_modification_time}")
            
        except Exception as e:
            print(f"Error modifying directory {dir_path}: {e}")
    
    def get_summary(self) -> dict:
        """
        Get modification summary
        
        Returns:
            Dictionary with modification statistics
        """
        return {
            "total_files_modified": len(self.modified_files),
            "modified_files": self.modified_files
        }


def main():
    """
    Command-line interface for file time modification
    """
    parser = argparse.ArgumentParser(
        description="Modify file creation and modification times"
    )
    
    parser.add_argument("directory", help="Target directory path")
    parser.add_argument("-y", "--years", type=int, default=0, help="Years to add/subtract")
    parser.add_argument("-m", "--months", type=int, default=0, help="Months to add/subtract")
    parser.add_argument("-d", "--days", type=int, default=0, help="Days to add/subtract")
    parser.add_argument("-H", "--hours", type=int, default=0, help="Hours to add/subtract")
    parser.add_argument("-o", "--operation", choices=["add", "subtract"], default="add", 
                       help="Operation: add or subtract")
    parser.add_argument("-r", "--recursive", action="store_true", 
                       help="Process subdirectories recursively")
    parser.add_argument("-p", "--pattern", help="File pattern (e.g., *.txt)")
    parser.add_argument("--dry-run", action="store_true", 
                       help="Show what would be modified without making changes")
    
    args = parser.parse_args()
    
    # Create modifier instance
    modifier = FileTimeModifier()
    
    try:
        if args.dry_run:
            print("DRY RUN - No changes will be made")
            print(f"Directory: {args.directory}")
            print(f"Operation: {args.operation}")
            print(f"Time delta: {args.years}y {args.months}m {args.days}d {args.hours}h")
            print(f"Recursive: {args.recursive}")
            print(f"Pattern: {args.pattern}")
            return
        
        # Modify file times
        modified_files = modifier.modify_file_times(
            directory=args.directory,
            years=args.years,
            months=args.months,
            days=args.days,
            hours=args.hours,
            operation=args.operation,
            recursive=args.recursive,
            file_pattern=args.pattern
        )
        
        # Print summary
        summary = modifier.get_summary()
        print(f"\nSummary:")
        print(f"Files modified: {summary['total_files_modified']}")
        
        if modified_files:
            print("\nModified files:")
            for file_path in modified_files:
                print(f"  {file_path}")
        
    except Exception as e:
        print(f"Error: {e}")
        return 1
    
    return 0


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