"""
Complete Eden Backup System - 8TB SSD Edition
"""
from pathlib import Path
import subprocess
import json
from datetime import datetime
import shutil

class EdenBackup:
    def __init__(self, backup_location='/Eden/EXTERNALS/Ava_Nyx/Eden_Backups'):
        self.backup_root = Path(backup_location)
        self.timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        self.backup_dir = self.backup_root / f'eden_backup_{self.timestamp}'
        
    def create_full_backup(self):
        """Create complete system backup on 8TB SSD"""
        print(f"🔄 Creating backup on 8TB SSD: {self.backup_dir}")
        self.backup_dir.mkdir(parents=True, exist_ok=True)
        
        manifest = {
            'timestamp': self.timestamp,
            'backup_date': datetime.now().isoformat(),
            'backup_location': '8TB SSD (/Eden/EXTERNALS/Ava_Nyx)',
            'components': {}
        }
        
        # 1. Backup all code
        print("📦 Backing up code...")
        code_backup = self.backup_dir / 'CORE'
        shutil.copytree('/Eden/CORE', code_backup, dirs_exist_ok=True)
        manifest['components']['code'] = {
            'path': 'CORE',
            'files': len(list(code_backup.rglob('*.py')))
        }
        
        # 2. Backup all data
        print("💾 Backing up data...")
        data_backup = self.backup_dir / 'DATA'
        if Path('/Eden/DATA').exists():
            shutil.copytree('/Eden/DATA', data_backup, dirs_exist_ok=True)
            manifest['components']['data'] = {
                'path': 'DATA',
                'files': len(list(data_backup.rglob('*')))
            }
        
        # 3. Backup all art
        print("🎨 Backing up art...")
        art_backup = self.backup_dir / 'ART'
        if Path('/Eden/ART').exists():
            shutil.copytree('/Eden/ART', art_backup, dirs_exist_ok=True)
            manifest['components']['art'] = {
                'path': 'ART',
                'files': len(list(art_backup.rglob('*')))
            }
        
        # 4. Backup learning data
        print("🧠 Backing up learning data...")
        if Path('/Eden/LEARNING').exists():
            learning_backup = self.backup_dir / 'LEARNING'
            shutil.copytree('/Eden/LEARNING', learning_backup, dirs_exist_ok=True)
            manifest['components']['learning'] = {
                'path': 'LEARNING',
                'files': len(list(learning_backup.rglob('*')))
            }
        
        # 5. Backup service files
        print("⚙️  Backing up services...")
        services_backup = self.backup_dir / 'SERVICES'
        services_backup.mkdir(exist_ok=True)
        
        for service in ['eden-core', 'eden-recursive', 'eden-multiagent']:
            try:
                service_file = f'/etc/systemd/system/{service}.service'
                if Path(service_file).exists():
                    shutil.copy(service_file, services_backup / f'{service}.service')
            except:
                pass
        
        manifest['components']['services'] = {
            'path': 'SERVICES',
            'count': len(list(services_backup.glob('*.service')))
        }
        
        # 6. Backup configuration files
        print("🔧 Backing up configs...")
        config_backup = self.backup_dir / 'CONFIG'
        config_backup.mkdir(exist_ok=True)
        
        configs = [
            '/Eden/CORE/mcp_config.json',
            '/Eden/AGI_COMPLETE.md',
            '/Eden/AGI_PROGRESS.md',
            '/Eden/AUTONOMOUS_GOALS_COMPLETE.md',
            '/Eden/EDEN_COMPLETE_SYSTEM.md',
            '/Eden/FINAL_ACHIEVEMENT.md'
        ]
        
        for config in configs:
            if Path(config).exists():
                shutil.copy(config, config_backup / Path(config).name)
        
        # 7. Save system state
        print("📊 Saving system state...")
        try:
            result = subprocess.run(['ollama', 'list'], capture_output=True, text=True, timeout=2)
            manifest['llms'] = [line.split()[0] for line in result.stdout.split('\n')[1:] if line]
        except:
            manifest['llms'] = []
        
        # Save manifest
        with open(self.backup_dir / 'MANIFEST.json', 'w') as f:
            json.dump(manifest, f, indent=2)
        
        # Create restore script
        self.create_restore_script()
        
        # Calculate backup size
        total_size = sum(f.stat().st_size for f in self.backup_dir.rglob('*') if f.is_file())
        manifest['total_size_mb'] = round(total_size / 1024 / 1024, 2)
        
        print(f"\n✅ Backup complete: {manifest['total_size_mb']} MB")
        print(f"📁 Location: {self.backup_dir}")
        print(f"💾 On 8TB SSD with {self.get_free_space()} TB free")
        
        return manifest
    
    def get_free_space(self):
        """Get free space on 8TB SSD"""
        result = subprocess.run(['df', '-h', '/Eden/EXTERNALS/Ava_Nyx'], 
                              capture_output=True, text=True)
        lines = result.stdout.split('\n')
        if len(lines) > 1:
            parts = lines[1].split()
            return parts[3] if len(parts) > 3 else "Unknown"
        return "Unknown"
    
    def create_restore_script(self):
        """Create script to restore from this backup"""
        restore_script = self.backup_dir / 'RESTORE.sh'
        
        script_content = f"""#!/bin/bash
# Eden Restore Script - From 8TB SSD
# Created: {datetime.now().isoformat()}

echo "🔄 Restoring Eden from 8TB SSD backup..."

# Stop services
sudo systemctl stop eden-core eden-recursive eden-multiagent

# Restore code
echo "📦 Restoring code..."
sudo cp -r {self.backup_dir}/CORE/* /Eden/CORE/

# Restore data
if [ -d "{self.backup_dir}/DATA" ]; then
    echo "💾 Restoring data..."
    sudo cp -r {self.backup_dir}/DATA/* /Eden/DATA/
fi

# Restore art
if [ -d "{self.backup_dir}/ART" ]; then
    echo "🎨 Restoring art..."
    sudo cp -r {self.backup_dir}/ART/* /Eden/ART/
fi

# Restore learning
if [ -d "{self.backup_dir}/LEARNING" ]; then
    echo "🧠 Restoring learning..."
    sudo cp -r {self.backup_dir}/LEARNING/* /Eden/LEARNING/
fi

# Restore services
if [ -d "{self.backup_dir}/SERVICES" ]; then
    echo "⚙️  Restoring services..."
    sudo cp {self.backup_dir}/SERVICES/*.service /etc/systemd/system/
    sudo systemctl daemon-reload
fi

# Restart services
echo "🚀 Restarting services..."
sudo systemctl start eden-core eden-recursive eden-multiagent

echo "✅ Restore complete from 8TB SSD!"
"""
        
        with open(restore_script, 'w') as f:
            f.write(script_content)
        
        restore_script.chmod(0o755)

# Create and run backup
backup = EdenBackup()
