#!/usr/bin/env python3
"""
Migration script to consolidate AnsibleExecution data into PlaybookExecution model
and deprecate the old model structure.
"""
import sys
import os
import uuid
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# Add the project root to Python path
sys.path.insert(0, '/home/pi/Desktop/Server_Monitorizare_v2')

from config.database_config import get_db
from app.models import AnsibleExecution, PlaybookExecution, PlaybookHostResult


class AutomationMigration:
    def __init__(self):
        from config.database_config import DatabaseConfig
        db_config = DatabaseConfig()
        self.engine = db_config.engine
        self.Session = sessionmaker(bind=self.engine)
    
    def migrate_executions(self):
        """Migrate data from AnsibleExecution to PlaybookExecution"""
        print("🔄 Starting automation model migration...")
        
        session = self.Session()
        try:
            # Get all existing AnsibleExecutions
            old_executions = session.query(AnsibleExecution).all()
            migrated_count = 0
            
            for old_exec in old_executions:
                # Check if already migrated
                existing = session.query(PlaybookExecution).filter_by(
                    playbook_name=old_exec.playbook_name,
                    start_time=old_exec.start_time
                ).first()
                
                if existing:
                    print(f"   ⏭️  Skipping {old_exec.playbook_name} (already migrated)")
                    continue
                
                # Create new PlaybookExecution from old data
                new_exec = PlaybookExecution(
                    execution_id=str(uuid.uuid4()),
                    playbook_name=old_exec.playbook_name,
                    target_hosts=old_exec.target_devices,
                    
                    # Timing
                    queued_at=old_exec.start_time,
                    started_at=old_exec.start_time,
                    completed_at=old_exec.end_time,
                    
                    # Status mapping
                    status=self._map_status(old_exec.status),
                    exit_code=old_exec.exit_code,
                    
                    # Logs
                    stdout_log=old_exec.stdout_log,
                    stderr_log=old_exec.stderr_log,
                    ansible_log_file=old_exec.ansible_log_file,
                    
                    # Results
                    successful_hosts=old_exec.successful_hosts,
                    failed_hosts=old_exec.failed_hosts,
                    unreachable_hosts=old_exec.unreachable_hosts,
                    total_hosts=old_exec.successful_hosts + old_exec.failed_hosts + old_exec.unreachable_hosts,
                    
                    # Metadata  
                    execution_user=old_exec.execution_user,
                    command_line=old_exec.command_line
                )
                
                session.add(new_exec)
                migrated_count += 1
                print(f"   ✅ Migrated: {old_exec.playbook_name} ({old_exec.start_time})")
            
            session.commit()
            print(f"\n✅ Migration completed: {migrated_count} executions migrated")
            
        except Exception as e:
            session.rollback()
            print(f"❌ Migration failed: {e}")
            raise
        finally:
            session.close()
    
    def _map_status(self, old_status):
        """Map old status values to new enum"""
        status_mapping = {
            'running': 'running',
            'completed': 'completed', 
            'failed': 'failed',
            'cancelled': 'cancelled'
        }
        return status_mapping.get(old_status, 'failed')
    
    def validate_migration(self):
        """Validate that migration was successful"""
        print("\n🔍 Validating migration...")
        
        session = self.Session()
        try:
            old_count = session.query(AnsibleExecution).count()
            new_count = session.query(PlaybookExecution).count()
            
            print(f"   📊 Old executions: {old_count}")
            print(f"   📊 New executions: {new_count}")
            
            if new_count >= old_count:
                print("   ✅ Migration validation passed")
                return True
            else:
                print("   ❌ Migration validation failed: data missing")
                return False
                
        except Exception as e:
            print(f"   ❌ Validation error: {e}")
            return False
        finally:
            session.close()
    
    def cleanup_old_tables(self, confirm=False):
        """Remove old AnsibleExecution table (use with caution)"""
        if not confirm:
            print("\n⚠️  Run with confirm=True to actually remove old table")
            print("   This will permanently delete AnsibleExecution data!")
            return
            
        print("\n🗑️  Cleaning up old AnsibleExecution table...")
        session = self.Session()
        try:
            session.query(AnsibleExecution).delete()
            session.commit()
            print("   ✅ Old execution data cleaned up")
        except Exception as e:
            session.rollback()
            print(f"   ❌ Cleanup failed: {e}")
        finally:
            session.close()


if __name__ == "__main__":
    migration = AutomationMigration()
    
    print("🔧 Automation Model Consolidation")
    print("=" * 50)
    
    # Step 1: Migrate data
    migration.migrate_executions()
    
    # Step 2: Validate
    if migration.validate_migration():
        print("\n🎉 Migration successful!")
        print("\nNext steps:")
        print("1. Test the new PlaybookExecution model")
        print("2. Update code to use only PlaybookExecution")
        print("3. Run cleanup_old_tables() when confident")
    else:
        print("\n❌ Migration validation failed!")
        sys.exit(1)