#!/usr/bin/env python
"""
Production deployment script for rollover enhancements
Handles migration issues and deploys the new rollover functionality
"""

import os
import sys
import django
from django.core.management import execute_from_command_line
from django.db import connection
from django.conf import settings

def setup_django():
    """Setup Django environment"""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
    django.setup()

def check_migration_status():
    """Check current migration status"""
    print("=== Checking Migration Status ===")
    
    with connection.cursor() as cursor:
        # Check if rollover_requests table exists
        cursor.execute("""
            SELECT COUNT(*) 
            FROM information_schema.tables 
            WHERE table_schema = DATABASE() 
            AND table_name = 'rollover_requests'
        """)
        table_exists = cursor.fetchone()[0] > 0
        
        if table_exists:
            # Check if rollover_date column exists
            cursor.execute("""
                SELECT COUNT(*) 
                FROM information_schema.columns 
                WHERE table_schema = DATABASE() 
                AND table_name = 'rollover_requests' 
                AND column_name = 'rollover_date'
            """)
            column_exists = cursor.fetchone()[0] > 0
            print(f"rollover_requests table exists: {table_exists}")
            print(f"rollover_date column exists: {column_exists}")
        else:
            print("rollover_requests table does not exist")
            column_exists = False
            
    return table_exists, column_exists

def fix_migration_history():
    """Fix inconsistent migration history"""
    print("\n=== Fixing Migration History ===")
    
    try:
        with connection.cursor() as cursor:
            # Check current migration status
            cursor.execute("""
                SELECT app, name, applied 
                FROM django_migrations 
                WHERE app IN ('users', 'loans') 
                ORDER BY app, id
            """)
            migrations = cursor.fetchall()
            
            print("Current migrations:")
            for app, name, applied in migrations:
                print(f"  {app}.{name}: {'Applied' if applied else 'Not Applied'}")
            
            # Check for the problematic migration
            cursor.execute("""
                SELECT COUNT(*) 
                FROM django_migrations 
                WHERE app = 'users' AND name = '0011_manual_add_is_default'
            """)
            has_0011 = cursor.fetchone()[0] > 0
            
            cursor.execute("""
                SELECT COUNT(*) 
                FROM django_migrations 
                WHERE app = 'users' AND name = '0010_add_enhanced_permissions'
            """)
            has_0010 = cursor.fetchone()[0] > 0
            
            if has_0011 and not has_0010:
                print("Found inconsistent migration history. Fixing...")
                
                # Remove the problematic migration record
                cursor.execute("""
                    DELETE FROM django_migrations 
                    WHERE app = 'users' AND name = '0011_manual_add_is_default'
                """)
                print("Removed users.0011_manual_add_is_default from migration history")
                
                # Try to apply migrations in correct order
                print("Applying migrations in correct order...")
                execute_from_command_line(['manage.py', 'migrate', 'users', '--fake-initial'])
                execute_from_command_line(['manage.py', 'migrate', 'users'])
                
            else:
                print("Migration history appears consistent")
                
    except Exception as e:
        print(f"Error fixing migration history: {e}")
        return False
    
    return True

def add_rollover_date_column():
    """Add rollover_date column directly to database"""
    print("\n=== Adding rollover_date Column ===")
    
    try:
        with connection.cursor() as cursor:
            # Check if column already exists
            cursor.execute("""
                SELECT COUNT(*) 
                FROM information_schema.columns 
                WHERE table_schema = DATABASE() 
                AND table_name = 'rollover_requests' 
                AND column_name = 'rollover_date'
            """)
            column_exists = cursor.fetchone()[0] > 0
            
            if not column_exists:
                # Add the column
                cursor.execute("""
                    ALTER TABLE rollover_requests 
                    ADD COLUMN rollover_date DATE NULL 
                    COMMENT 'Preferred rollover date'
                """)
                print("Added rollover_date column to rollover_requests table")
            else:
                print("rollover_date column already exists")
                
    except Exception as e:
        print(f"Error adding rollover_date column: {e}")
        return False
    
    return True

def create_fake_migration():
    """Create a fake migration record for the rollover_date field"""
    print("\n=== Creating Fake Migration Record ===")
    
    try:
        with connection.cursor() as cursor:
            # Check if migration record already exists
            cursor.execute("""
                SELECT COUNT(*) 
                FROM django_migrations 
                WHERE app = 'loans' AND name = '0018_add_rollover_date_field'
            """)
            migration_exists = cursor.fetchone()[0] > 0
            
            if not migration_exists:
                # Insert fake migration record
                cursor.execute("""
                    INSERT INTO django_migrations (app, name, applied) 
                    VALUES ('loans', '0018_add_rollover_date_field', NOW())
                """)
                print("Created fake migration record for rollover_date field")
            else:
                print("Migration record already exists")
                
    except Exception as e:
        print(f"Error creating fake migration record: {e}")
        return False
    
    return True

def run_migrations():
    """Run Django migrations"""
    print("\n=== Running Django Migrations ===")
    
    try:
        # Run migrations for all apps
        execute_from_command_line(['manage.py', 'migrate', '--noinput'])
        print("All migrations completed successfully")
        return True
    except Exception as e:
        print(f"Error running migrations: {e}")
        return False

def verify_deployment():
    """Verify the deployment was successful"""
    print("\n=== Verifying Deployment ===")
    
    try:
        # Check if rollover_date column exists
        table_exists, column_exists = check_migration_status()
        
        if table_exists and column_exists:
            print("SUCCESS: rollover_date column is present")
            
            # Test the model
            from loans.models import RolloverRequest
            fields = [field.name for field in RolloverRequest._meta.fields]
            if 'rollover_date' in fields:
                print("SUCCESS: RolloverRequest model has rollover_date field")
            else:
                print("ERROR: RolloverRequest model missing rollover_date field")
                return False
                
        else:
            print("ERROR: rollover_date column is missing")
            return False
            
        print("SUCCESS: Rollover enhancements deployed successfully!")
        return True
        
    except Exception as e:
        print(f"Error verifying deployment: {e}")
        return False

def main():
    """Main deployment function"""
    print("=== Production Deployment: Rollover Enhancements ===")
    print("This script will deploy the enhanced rollover functionality with date field")
    print("and add Complete History buttons to client popup and loan detail pages.\n")
    
    try:
        # Setup Django
        setup_django()
        
        # Check current status
        table_exists, column_exists = check_migration_status()
        
        # Fix migration history if needed
        if not fix_migration_history():
            print("ERROR: Failed to fix migration history")
            return False
        
        # Add rollover_date column if needed
        if not column_exists:
            if not add_rollover_date_column():
                print("ERROR: Failed to add rollover_date column")
                return False
        
        # Create fake migration record
        if not create_fake_migration():
            print("ERROR: Failed to create fake migration record")
            return False
        
        # Run migrations
        if not run_migrations():
            print("ERROR: Failed to run migrations")
            return False
        
        # Verify deployment
        if not verify_deployment():
            print("ERROR: Deployment verification failed")
            return False
        
        print("\n=== Deployment Complete ===")
        print("SUCCESS: All rollover enhancements have been deployed!")
        print("Features deployed:")
        print("  - Enhanced rollover form with date field")
        print("  - Complete History button in client popup")
        print("  - Complete History button in loan detail pages")
        print("  - Database migration for rollover_date field")
        
        return True
        
    except Exception as e:
        print(f"ERROR: Deployment failed with exception: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
