"""
File management utilities for handling uploads and storage
"""

import os
import shutil
import hashlib
from pathlib import Path
from datetime import datetime, timedelta
import asyncio
from typing import Optional
import logging

# Fix the import path issue
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from config import (
    TEMP_UPLOAD_DIR, 
    VALID_UPLOAD_DIR, 
    ALLOWED_EXTENSIONS,
    TEMP_FILE_CLEANUP_HOURS
)

logger = logging.getLogger(__name__)


class FileManager:
    """
    Manages file operations for uploaded images including:
    - Validation
    - Temporary storage
    - Moving to permanent storage
    - Cleanup of old files
    - Duplicate detection
    """
    
    _image_hashes = None
    
    @staticmethod
    def calculate_image_hash(image_path: str) -> str:
        """
        Calculate MD5 hash of an image file for duplicate detection.
        
        Args:
            image_path: Path to the image file
            
        Returns:
            MD5 hash of the image file
        """
        hash_md5 = hashlib.md5()
        with open(image_path, "rb") as f:
            for chunk in iter(lambda: f.read(4096), b""):
                hash_md5.update(chunk)
        return hash_md5.hexdigest()
    
    @staticmethod
    def is_duplicate_image(image_hash: str) -> bool:
        """
        Check if an image hash already exists (duplicate detection).
        
        Args:
            image_hash: MD5 hash of the image
            
        Returns:
            True if duplicate, False otherwise
        """
        return False
    
    @staticmethod
    def register_image_hash(image_hash: str, filename: str):
        """
        Register an image hash to track uploaded images.
        
        Args:
            image_hash: MD5 hash of the image
            filename: Name of the image file
        """
        return
    
    @staticmethod
    def validate_file_extension(filename: str) -> bool:
        """
        Check if file has an allowed extension.
        
        Args:
            filename: Name of the file to validate
            
        Returns:
            True if extension is allowed, False otherwise
        """
        ext = Path(filename).suffix.lower()
        return ext in ALLOWED_EXTENSIONS
    
    @staticmethod
    def validate_file_size(file_size: int, max_size: int) -> bool:
        """
        Check if file size is within allowed limit.
        
        Args:
            file_size: Size of file in bytes
            max_size: Maximum allowed size in bytes
            
        Returns:
            True if size is acceptable, False otherwise
        """
        return file_size <= max_size
    
    @staticmethod
    def generate_unique_filename(original_filename: str) -> str:
        """
        Generate a unique filename using timestamp.
        
        Args:
            original_filename: Original name of the uploaded file
            
        Returns:
            Unique filename with timestamp
        """
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
        ext = Path(original_filename).suffix
        name = Path(original_filename).stem
        return f"{name}_{timestamp}{ext}"
    
    @staticmethod
    async def save_temp_file(file_content: bytes, filename: str) -> Path:
        """
        Save uploaded file to temporary storage.
        
        Args:
            file_content: Binary content of the file
            filename: Name for the file
            
        Returns:
            Path to the saved file
        """
        try:
            file_path = TEMP_UPLOAD_DIR / filename
            
            # Write file asynchronously
            with open(file_path, "wb") as f:
                f.write(file_content)
            
            logger.info(f"File saved to temp storage: {filename}")
            return file_path
            
        except Exception as e:
            logger.error(f"Error saving temp file: {e}")
            raise
    
    @staticmethod
    def move_to_valid_storage(temp_path: Path) -> Path:
        """
        Move a verified image from temp to permanent storage.
        
        Args:
            temp_path: Path to file in temp storage
            
        Returns:
            Path to file in permanent storage
        """
        try:
            valid_path = VALID_UPLOAD_DIR / temp_path.name
            shutil.move(str(temp_path), str(valid_path))
            logger.info(f"File moved to valid storage: {temp_path.name}")
            return valid_path
            
        except Exception as e:
            logger.error(f"Error moving file to valid storage: {e}")
            raise
    
    @staticmethod
    def delete_file(file_path: Path) -> bool:
        """
        Delete a file from storage.
        
        Args:
            file_path: Path to file to delete
            
        Returns:
            True if deleted successfully, False otherwise
        """
        try:
            if file_path.exists():
                file_path.unlink()
                logger.info(f"File deleted: {file_path.name}")
                return True
            return False
            
        except Exception as e:
            logger.error(f"Error deleting file: {e}")
            return False
    
    @staticmethod
    async def cleanup_old_temp_files():
        """
        Delete temporary files older than the configured cleanup time.
        This runs as a background task.
        """
        while True:
            try:
                cutoff_time = datetime.now() - timedelta(hours=TEMP_FILE_CLEANUP_HOURS)
                
                for file_path in TEMP_UPLOAD_DIR.glob("*"):
                    if file_path.is_file():
                        # Get file modification time
                        file_mtime = datetime.fromtimestamp(file_path.stat().st_mtime)
                        
                        # Delete if older than cutoff
                        if file_mtime < cutoff_time:
                            FileManager.delete_file(file_path)
                            logger.info(f"Cleaned up old temp file: {file_path.name}")
                
                # Run cleanup every 30 minutes
                await asyncio.sleep(1800)
                
            except Exception as e:
                logger.error(f"Error during temp file cleanup: {e}")
                await asyncio.sleep(1800)
    
    @staticmethod
    def get_storage_stats() -> dict:
        """
        Get statistics about storage usage.
        
        Returns:
            Dictionary with storage statistics
        """
        try:
            temp_files = list(TEMP_UPLOAD_DIR.glob("*"))
            valid_files = list(VALID_UPLOAD_DIR.glob("*"))
            
            temp_size = sum(f.stat().st_size for f in temp_files if f.is_file())
            valid_size = sum(f.stat().st_size for f in valid_files if f.is_file())
            
            return {
                "temp_files_count": len(temp_files),
                "valid_files_count": len(valid_files),
                "temp_storage_mb": round(temp_size / (1024 * 1024), 2),
                "valid_storage_mb": round(valid_size / (1024 * 1024), 2)
            }
            
        except Exception as e:
            logger.error(f"Error getting storage stats: {e}")
            return {}