"""
Dual Backup System - Backup to BOTH SSDs
"""
from pathlib import Path
import subprocess
import json
from datetime import datetime
import shutil

class DualBackup:
    def __init__(self):
        self.timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        self.locations = [
            '/Eden/EXTERNALS/Ava_Nyx/Eden_Backups',  # 8TB SSD
            '/Eden/EXTERNALS/4TB_Backup/Eden_Backups'  # 4TB SSD
        ]
    
    def backup_to_location(self, location: str) -> dict:
        """Backup to specific location"""
        backup_root = Path(location)
        backup_dir = backup_root / f'eden_backup_{self.timestamp}'
        
        print(f"\n🔄 Backing up to: {location}")
        backup_dir.mkdir(parents=True, exist_ok=True)
        
        manifest = {
            'timestamp': self.timestamp,
            'backup_date': datetime.now().isoformat(),
            'location': location,
            'components': {}
        }
        
        # Backup all directories
        dirs_to_backup = [
            ('/Eden/CORE', 'CORE'),
            ('/Eden/DATA', 'DATA'),
            ('/Eden/ART', 'ART'),
            ('/Eden/LEARNING', 'LEARNING')
        ]
        
        for source, name in dirs_to_backup:
            if Path(source).exists():
                print(f"   📦 {name}...")
                dest = backup_dir / name
                shutil.copytree(source, dest, dirs_exist_ok=True)
                manifest['components'][name.lower()] = {
                    'files': len(list(dest.rglob('*')))
                }
        
        # Backup services
        print("   ⚙️  Services...")
        services_backup = 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
        
        # Backup configs
        print("   🔧 Configs...")
        config_backup = backup_dir / 'CONFIG'
        config_backup.mkdir(exist_ok=True)
        
        for config_file in Path('/Eden').glob('*.md'):
            shutil.copy(config_file, config_backup / config_file.name)
        
        # Save manifest
        with open(backup_dir / 'MANIFEST.json', 'w') as f:
            json.dump(manifest, f, indent=2)
        
        # Create restore script
        self.create_restore_script(backup_dir)
        
        # Calculate size
        total_size = sum(f.stat().st_size for f in backup_dir.rglob('*') if f.is_file())
        manifest['total_size_mb'] = round(total_size / 1024 / 1024, 2)
        
        print(f"   ✅ Complete: {manifest['total_size_mb']} MB")
        
        return manifest
    
    def create_restore_script(self, backup_dir: Path):
        """Create restore script"""
        restore_script = backup_dir / 'RESTORE.sh'
        
        script = f"""#!/bin/bash
echo "🔄 Restoring Eden..."
sudo systemctl stop eden-core eden-recursive eden-multiagent

sudo cp -r {backup_dir}/CORE/* /Eden/CORE/
[ -d "{backup_dir}/DATA" ] && sudo cp -r {backup_dir}/DATA/* /Eden/DATA/
[ -d "{backup_dir}/ART" ] && sudo cp -r {backup_dir}/ART/* /Eden/ART/
[ -d "{backup_dir}/LEARNING" ] && sudo cp -r {backup_dir}/LEARNING/* /Eden/LEARNING/
[ -d "{backup_dir}/SERVICES" ] && sudo cp {backup_dir}/SERVICES/*.service /etc/systemd/system/ && sudo systemctl daemon-reload

sudo systemctl start eden-core eden-recursive eden-multiagent
echo "✅ Restored!"
"""
        
        with open(restore_script, 'w') as f:
            f.write(script)
        restore_script.chmod(0o755)
    
    def backup_all(self):
        """Backup to all locations"""
        print("💾 DUAL BACKUP - Creating redundant backups")
        results = []
        
        for location in self.locations:
            if Path(location).parent.exists():
                try:
                    manifest = self.backup_to_location(location)
                    results.append(manifest)
                except Exception as e:
                    print(f"   ❌ Failed: {e}")
            else:
                print(f"   ⚠️  Skipped (not mounted): {location}")
        
        return results

backup = DualBackup()
