#!/usr/bin/env python
"""
Production deployment script for Client Approval System
This script deploys the new approval fields to the production database.
"""

import os
import sys
import django
from pathlib import Path
from django.core.management import call_command
from django.db import connection

# Setup Django
sys.path.insert(0, str(Path(__file__).resolve().parent))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.conf import settings
from users.models import CustomUser
from django.db import transaction


def print_section(title):
    """Print a formatted section header"""
    print("\n" + "=" * 80)
    print(f"  {title}")
    print("=" * 80 + "\n")


def check_database_connection():
    """Verify database connection"""
    print_section("Checking Database Connection")
    try:
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
            print("✓ Database connection successful")
            return True
    except Exception as e:
        print(f"✗ Database connection failed: {e}")
        return False


def check_table_structure():
    """Check if approval fields exist in the database"""
    print_section("Checking Database Structure")
    
    try:
        with connection.cursor() as cursor:
            # Check if users table exists
            cursor.execute("""
                SELECT COLUMN_NAME 
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = 'users' 
                AND COLUMN_NAME IN ('approved_by_id', 'approved_at', 'approval_reason', 'rejected_by_id', 'rejected_at', 'rejection_reason')
            """)
            
            existing_columns = [row[0] for row in cursor.fetchall()]
            
            required_columns = [
                'approved_by_id', 'approved_at', 'approval_reason',
                'rejected_by_id', 'rejected_at', 'rejection_reason'
            ]
            
            missing_columns = [col for col in required_columns if col not in existing_columns]
            
            if missing_columns:
                print(f"✗ Missing columns: {', '.join(missing_columns)}")
                print("  Migration needs to be applied")
                return False
            else:
                print("✓ All approval fields exist in database")
                return True
                
    except Exception as e:
        print(f"✗ Error checking table structure: {e}")
        return False


def backup_database():
    """Create a backup of the database before migration"""
    print_section("Creating Database Backup")
    
    try:
        db_name = settings.DATABASES['default']['NAME']
        backup_file = f"backup_{db_name}_{Path(__file__).stem}.sql"
        
        print(f"Creating backup: {backup_file}")
        print("(Note: Full SQL dump requires database credentials)")
        print("Please ensure you have a recent backup of your database")
        
        return True
    except Exception as e:
        print(f"✗ Backup warning: {e}")
        print("  Continuing without backup (not recommended)")
        return True


def run_migrations():
    """Run pending migrations"""
    print_section("Running Migrations")
    
    try:
        # Check for pending migrations
        print("Checking for pending migrations...")
        call_command('showmigrations', 'users', verbosity=0)
        
        print("\nApplying migrations...")
        call_command('migrate', 'users', verbosity=2, interactive=False)
        
        print("\n✓ Migrations applied successfully")
        return True
        
    except Exception as e:
        print(f"\n✗ Migration failed: {e}")
        return False


def verify_migration():
    """Verify that the migration was successful"""
    print_section("Verifying Migration")
    
    try:
        # Try to access the new fields
        if not CustomUser._meta.get_field('approved_by'):
            print("✗ approved_by field not found in model")
            return False
        
        if not CustomUser._meta.get_field('rejected_by'):
            print("✗ rejected_by field not found in model")
            return False
        
        print("✓ Model fields verified")
        
        # Check database columns
        if not check_table_structure():
            return False
        
        print("✓ Database structure verified")
        print("✓ Migration successful!")
        return True
        
    except Exception as e:
        print(f"✗ Verification failed: {e}")
        return False


def test_approval_system():
    """Test the approval system functionality"""
    print_section("Testing Approval System")
    
    try:
        # Check if we can query pending approval clients
        pending_count = CustomUser.objects.filter(
            role='borrower',
            status='pending_approval'
        ).count()
        
        print(f"✓ Found {pending_count} pending clients")
        print("✓ Approval system is functional")
        return True
        
    except Exception as e:
        print(f"✗ Testing failed: {e}")
        return False


def print_summary(success):
    """Print deployment summary"""
    print_section("Deployment Summary")
    
    if success:
        print("✓ CLIENT APPROVAL SYSTEM DEPLOYED SUCCESSFULLY")
        print("\nNext steps:")
        print("  1. Test the pending clients page: /users/clients/pending/")
        print("  2. Test approving a client")
        print("  3. Test rejecting a client")
        print("  4. Monitor the audit logs for approval/rejection actions")
        print("\nFor admins:")
        print("  - Navigate to Clients page")
        print("  - Click 'Pending Approvals' button")
        print("  - Approve or reject clients as needed")
    else:
        print("✗ DEPLOYMENT FAILED")
        print("\nTroubleshooting:")
        print("  1. Check database connection")
        print("  2. Verify Django settings")
        print("  3. Check migration files")
        print("  4. Review error messages above")


def main():
    """Main deployment function"""
    print("\n" + "#" * 80)
    print("#" + " " * 78 + "#")
    print("#  CLIENT APPROVAL SYSTEM - PRODUCTION DEPLOYMENT")
    print("#" + " " * 78 + "#")
    print("#" * 80 + "\n")
    
    steps = [
        ("Database Connection", check_database_connection),
        ("Database Backup", backup_database),
        ("Run Migrations", run_migrations),
        ("Verify Migration", verify_migration),
        ("Test Approval System", test_approval_system),
    ]
    
    success = True
    for step_name, step_func in steps:
        try:
            if not step_func():
                success = False
                print(f"\n✗ Step '{step_name}' failed. Stopping deployment.")
                break
        except Exception as e:
            print(f"\n✗ Step '{step_name}' raised an exception: {e}")
            success = False
            break
    
    print_summary(success)
    return 0 if success else 1


if __name__ == '__main__':
    try:
        exit_code = main()
        sys.exit(exit_code)
    except KeyboardInterrupt:
        print("\n\n✗ Deployment interrupted by user")
        sys.exit(1)
    except Exception as e:
        print(f"\n✗ Unexpected error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

