#!/usr/bin/env python3
"""
Enhanced backup script for PHP migration tracking system.
Creates comprehensive backups including the migration database.
"""

import os
import zipfile
from datetime import datetime
from pathlib import Path

def create_backup(include_vmserver10: bool = False, backup_dir: str = None):
    """
    Create comprehensive backup of migration tracking system.
    
    Args:
        include_vmserver10: Whether to include vmserver10 directory
        backup_dir: Custom backup directory path
    """
    # Backup directory
    if backup_dir is None:
        backup_dir = '../Backups'
    
    if not os.path.exists(backup_dir):
        os.makedirs(backup_dir)

    # Backup file name with timestamp
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    backup_type = 'full' if include_vmserver10 else 'migration'
    backup_file = os.path.join(backup_dir, f'{backup_type}_backup_{timestamp}.zip')

    print(f"🔄 Creating {backup_type} backup...")
    
    # Files and directories to include
    items_to_backup = []
    
    # Always include these directories/files
    base_items = [
        'Tools',
        'Progress',
        'AI_DATA',
        'AI_info.md',
        'project_plan.md'
    ]
    
    # Add vmserver10 if requested
    if include_vmserver10:
        base_items.append('vmserver10')
    
    # Check which items exist and add them
    for item in base_items:
        item_path = os.path.join('..', item)
        if os.path.exists(item_path):
            items_to_backup.append(item_path)
    
    # Create zip file
    files_added = 0
    with zipfile.ZipFile(backup_file, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for item_path in items_to_backup:
            if os.path.isfile(item_path):
                # Single file
                arcname = os.path.relpath(item_path, '..')
                zipf.write(item_path, arcname)
                files_added += 1
            elif os.path.isdir(item_path):
                # Directory - walk through it
                for root, dirs, files in os.walk(item_path):
                    # Skip hidden directories and backup directories
                    dirs[:] = [d for d in dirs if not d.startswith('.') and d.lower() != 'backups']
                    
                    for file in files:
                        # Skip hidden files and temporary files
                        if file.startswith('.') or file.endswith('.tmp'):
                            continue
                        
                        file_path = os.path.join(root, file)
                        arcname = os.path.relpath(file_path, '..')
                        zipf.write(file_path, arcname)
                        files_added += 1
    
    # Get backup file size
    backup_size = os.path.getsize(backup_file)
    size_mb = backup_size / (1024 * 1024)
    
    print(f"✅ Backup created: {backup_file}")
    print(f"   Files included: {files_added}")
    print(f"   Backup size: {size_mb:.1f} MB")
    
    return backup_file

def create_database_backup(backup_dir: str = None):
    """
    Create a backup of just the migration database.
    
    Args:
        backup_dir: Custom backup directory path
    """
    if backup_dir is None:
        backup_dir = '../Backups'
    
    if not os.path.exists(backup_dir):
        os.makedirs(backup_dir)
    
    db_path = os.path.join(os.path.dirname(__file__), 'migration.db')
    
    if not os.path.exists(db_path):
        print("⚠️  Migration database not found - nothing to backup")
        return None
    
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    backup_file = os.path.join(backup_dir, f'migration_db_{timestamp}.db')
    
    # Copy database file
    import shutil
    shutil.copy2(db_path, backup_file)
    
    backup_size = os.path.getsize(backup_file)
    size_kb = backup_size / 1024
    
    print(f"✅ Database backup created: {backup_file}")
    print(f"   Database size: {size_kb:.1f} KB")
    
    return backup_file

def list_backups(backup_dir: str = None):
    """
    List available backups with details.
    
    Args:
        backup_dir: Backup directory to scan
    """
    if backup_dir is None:
        backup_dir = '../Backups'
    
    if not os.path.exists(backup_dir):
        print("No backup directory found")
        return
    
    backup_files = []
    for file in os.listdir(backup_dir):
        if file.endswith(('.zip', '.db')):
            file_path = os.path.join(backup_dir, file)
            stat = os.stat(file_path)
            backup_files.append({
                'name': file,
                'path': file_path,
                'size': stat.st_size,
                'modified': datetime.fromtimestamp(stat.st_mtime)
            })
    
    if not backup_files:
        print("No backup files found")
        return
    
    # Sort by modification time (newest first)
    backup_files.sort(key=lambda x: x['modified'], reverse=True)
    
    print(f"📦 Available backups in {backup_dir}:")
    print()
    
    for backup in backup_files:
        size_mb = backup['size'] / (1024 * 1024)
        modified_str = backup['modified'].strftime('%Y-%m-%d %H:%M:%S')
        
        backup_type = "🗃️  Database" if backup['name'].endswith('.db') else "📁 Full Archive"
        print(f"{backup_type}: {backup['name']}")
        print(f"   Size: {size_mb:.1f} MB")
        print(f"   Created: {modified_str}")
        print()

def main():
    """Main backup function with command line interface."""
    import argparse
    
    parser = argparse.ArgumentParser(description='Create backups of migration tracking system')
    parser.add_argument('--include-vmserver10', action='store_true', 
                       help='Include vmserver10 directory in backup (creates larger backup)')
    parser.add_argument('--database-only', action='store_true',
                       help='Backup only the migration database')
    parser.add_argument('--list', action='store_true',
                       help='List available backups')
    parser.add_argument('--backup-dir', default='../Backups',
                       help='Custom backup directory')
    
    args = parser.parse_args()
    
    print("📦 PHP Migration Backup System")
    print("=" * 40)
    
    if args.list:
        list_backups(args.backup_dir)
    elif args.database_only:
        create_database_backup(args.backup_dir)
    else:
        create_backup(args.include_vmserver10, args.backup_dir)

if __name__ == '__main__':
    main()