import sys
from pathlib import Path
from ws_package.log.writer import LogWriter
from ws_package.configs import config
import time
logger = LogWriter.file(__name__)

def cleanup_old_files(directory):
    """
    Clean up old files in logsy directory with age-based and count-based deletion.
    Works offline - doesn't require server connectivity.
    """
    logger.info("Cleaning up old files in %s", directory)
    try:
        dir_path = Path(directory)  # Convert to a Path object
        if not dir_path.exists() or not dir_path.is_dir():
            logger.debug("Directory not found or not a directory: %s", directory)
            return

        # Get retention settings from config
        retention_days = config('log_retention_days', 'System', dtype='int') or 30
        max_files = config('logsy_max_files', 'System', dtype='int') or 50
        
        files = [file for file in dir_path.iterdir() if file.is_file()]
        
        if not files:
            return
        
        # Calculate cutoff time for age-based deletion
        cutoff_time = time.time() - (retention_days * 24 * 3600)
        
        deleted_count = 0
        deleted_size = 0
        
        # First pass: Delete files older than retention period
        for file in files:
            try:
                file_mtime = file.stat().st_mtime
                if file_mtime < cutoff_time:
                    file_size = file.stat().st_size
                    file.unlink()
                    deleted_count += 1
                    deleted_size += file_size
                    logger.debug("Deleted old file (age-based): %s (%s MB)", file.name, file_size / 1024 / 1024)
            except Exception as e:
                logger.debug("Error deleting file %s: %s", file.name, e)
        
        # Second pass: If still too many files, delete oldest ones (count-based)
        remaining_files = [file for file in dir_path.iterdir() if file.is_file()]
        if len(remaining_files) > max_files:
            # Sort by modification time (oldest first)
            remaining_files.sort(key=lambda f: f.stat().st_mtime)
            files_to_delete = remaining_files[:-max_files]  # Keep only the N most recent
            
            for file in files_to_delete:
                try:
                    file_size = file.stat().st_size
                    file.unlink()
                    deleted_count += 1
                    deleted_size += file_size
                    logger.debug("Deleted old file (count-based): %s (%s MB)", file.name, file_size / 1024 / 1024)
                except Exception as e:
                    logger.debug("Error deleting file %s: %s", file.name, e)
        
        if deleted_count > 0:
            logger.info("Log cleanup completed: Deleted %s file(s), freed %s MB", deleted_count, deleted_size / 1024 / 1024)
        else:
            logger.debug("Log cleanup: No files to delete (retention: %s days, max files: %s)", retention_days, max_files)

    except FileNotFoundError as e:
        logger.debug("Directory not found: %s", e)
    except PermissionError:
        logger.warning("Error: Permission denied during log cleanup. Try running with elevated privileges.")
    except Exception as e:
        logger.error("An unexpected error occurred during log cleanup: %s", e, exc_info=True)

def cleanup_old_files_mac():
    """Clean up log files in the macOS log directory."""
    if sys.platform != "darwin":
        raise RuntimeError("cleanup_old_files_mac is only supported on macOS")
    log_dir = Path.home() / "Library/Application Support/Workstatus/logsy"
    try:
        log_dir.mkdir(parents=True, exist_ok=True)
    except Exception as e:
        logger.warning("Failed to create log directory: %s", e)
        return
    cleanup_old_files(str(log_dir))

def cleanup_thread_log_backups():
    """
    Clean up old thread log backup files (device.log.1, push.log.1, etc.).
    Works offline - doesn't require server connectivity.
    """
    try:
        # Get log directory
        from ws_package.log.writer import get_log_directory
        log_dir = get_log_directory()
        
        # Get retention settings from config
        retention_days = config('thread_log_retention_days', 'System', dtype='int') or 30
        
        if not log_dir.exists():
            return
        
        # Calculate cutoff time for age-based deletion
        cutoff_time = time.time() - (retention_days * 24 * 3600)
        
        deleted_count = 0
        deleted_size = 0
        
        # Find all backup log files (files ending with .1, .2, .3, etc.)
        backup_files = []
        for file in log_dir.glob("*.log.*"):
            try:
                # Check if it's a backup file (has numeric extension)
                parts = file.name.rsplit('.', 2)
                if len(parts) >= 2 and parts[-1].isdigit():
                    backup_files.append(file)
            except Exception:
                continue
        
        # Delete backup files older than retention period
        for file in backup_files:
            try:
                file_mtime = file.stat().st_mtime
                if file_mtime < cutoff_time:
                    file_size = file.stat().st_size
                    file.unlink()
                    deleted_count += 1
                    deleted_size += file_size
                    logger.debug("Deleted old thread log backup (age-based): %s (%s MB)", file.name, file_size / 1024 / 1024)
            except Exception as e:
                logger.debug("Error deleting thread log backup %s: %s", file.name, e)
        
        if deleted_count > 0:
            logger.info("Thread log cleanup completed: Deleted %s backup file(s), freed %s MB", deleted_count, deleted_size / 1024 / 1024)
        else:
            logger.debug("Thread log cleanup: No backup files to delete (retention: %s days)", retention_days)
    
    except Exception as e:
        logger.error("Error during thread log backup cleanup: %s", e, exc_info=True)

def perform_comprehensive_log_cleanup():
    """
    Perform comprehensive log cleanup for all log directories.
    Works offline - doesn't require server connectivity.
    """
    try:
        logger.info("Starting comprehensive log cleanup...")
        
        # Clean up logsy directory (Windows)
        if sys.platform == "win32":
            try:
                if getattr(sys, 'frozen', False):
                    target_directory = Path(sys.executable).resolve().parent
                    logsy_dir = target_directory / "logsy"
                    if logsy_dir.exists():
                        cleanup_old_files(str(logsy_dir))
            except Exception as e:
                logger.debug("Error cleaning Windows logsy directory: %s", e)
        
        # Clean up logsy directory (macOS)
        if sys.platform == "darwin":
            try:
                cleanup_old_files_mac()
            except Exception as e:
                logger.debug("Error cleaning macOS logsy directory: %s", e)
        
        # Clean up thread log backups
        try:
            cleanup_thread_log_backups()
        except Exception as e:
            logger.debug("Error cleaning thread log backups: %s", e)
        
        logger.info("Comprehensive log cleanup completed")
    
    except Exception as e:
        logger.error("Error during comprehensive log cleanup: %s", e, exc_info=True)


