"""
Automated Daily Backup System
"""
from pathlib import Path
import subprocess
import json
from datetime import datetime
import shutil
import sys

class AutomatedBackup:
    def __init__(self):
        self.timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        self.log_file = Path('/Eden/DATA/backup_log.json')
        self.locations = [
            '/Eden/EXTERNALS/Ava_Nyx/Eden_Backups',
            '/Eden/EXTERNALS/4TB_Backup/Eden_Backups'
        ]
        
    def cleanup_old_backups(self, location: str, keep_count: int = 7):
        """Keep only last N backups"""
        backup_root = Path(location)
        if not backup_root.exists():
            return
        
        backups = sorted(backup_root.glob('eden_backup_*'), key=lambda x: x.stat().st_mtime, reverse=True)
        
        for old_backup in backups[keep_count:]:
            print(f"   🗑️  Removing old: {old_backup.name}")
            shutil.rmtree(old_backup)
    
    def backup_to_location(self, location: str) -> dict:
        """Backup to specific location"""
        backup_root = Path(location)
        
        if not backup_root.parent.exists():
            return {'status': 'skipped', 'reason': 'drive not mounted'}
        
        backup_dir = backup_root / f'eden_backup_{self.timestamp}'
        backup_dir.mkdir(parents=True, exist_ok=True)
        
        manifest = {
            'timestamp': self.timestamp,
            'date': datetime.now().isoformat(),
            'location': location,
            'status': 'success',
            'components': {}
        }
        
        try:
            # Backup 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():
                    dest = backup_dir / name
                    shutil.copytree(source, dest, dirs_exist_ok=True)
                    manifest['components'][name.lower()] = {
                        'files': len(list(dest.rglob('*')))
                    }
            
            # Backup services
            services_backup = backup_dir / 'SERVICES'
            services_backup.mkdir(exist_ok=True)
            
            for service in ['eden-core', 'eden-recursive', 'eden-multiagent']:
                service_file = Path(f'/etc/systemd/system/{service}.service')
                if service_file.exists():
                    shutil.copy(service_file, services_backup / f'{service}.service')
            
            # Calculate size
            total_size = sum(f.stat().st_size for f in backup_dir.rglob('*') if f.is_file())
            manifest['size_mb'] = round(total_size / 1024 / 1024, 2)
            
            # Create restore script
            self._create_restore_script(backup_dir)
            
            # Save manifest
            with open(backup_dir / 'MANIFEST.json', 'w') as f:
                json.dump(manifest, f, indent=2)
            
            # Cleanup old backups (keep last 7 days)
            self.cleanup_old_backups(location, keep_count=7)
            
        except Exception as e:
            manifest['status'] = 'failed'
            manifest['error'] = str(e)
        
        return manifest
    
    def _create_restore_script(self, backup_dir: Path):
        """Create restore script"""
        script = backup_dir / 'RESTORE.sh'
        content = f"""#!/bin/bash
echo "🔄 Restoring from {backup_dir}..."
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(script, 'w') as f:
            f.write(content)
        script.chmod(0o755)
    
    def log_backup(self, results: list):
        """Log backup results"""
        logs = []
        if self.log_file.exists():
            with open(self.log_file) as f:
                logs = json.load(f)
        
        logs.append({
            'timestamp': datetime.now().isoformat(),
            'results': results
        })
        
        # Keep last 30 days of logs
        logs = logs[-30:]
        
        self.log_file.parent.mkdir(exist_ok=True)
        with open(self.log_file, 'w') as f:
            json.dump(logs, f, indent=2)
    
    def run_backup(self):
        """Run automated backup"""
        print(f"🤖 Automated Backup Started: {datetime.now()}")
        results = []
        
        for location in self.locations:
            print(f"\n💾 Backing up to: {location}")
            result = self.backup_to_location(location)
            results.append(result)
            
            if result['status'] == 'success':
                print(f"   ✅ {result['size_mb']} MB")
            else:
                print(f"   ❌ {result.get('reason', result.get('error', 'Unknown'))}")
        
        self.log_backup(results)
        print(f"\n✅ Automated Backup Complete: {datetime.now()}")
        return results

if __name__ == '__main__':
    backup = AutomatedBackup()
    backup.run_backup()
