#!/usr/bin/env python
"""
Complete M-Pesa Deployment Script
This script handles all deployment scenarios including missing fields.
"""
import os
import sys
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.core.management import call_command
from django.db import connection
from payments.branch_mpesa_service import BranchMpesaService
from users.models import Branch

def check_mpesa_fields():
    """Check if M-Pesa fields exist in Branch model"""
    print("🔄 Checking M-Pesa fields...")
    try:
        with connection.cursor() as cursor:
            cursor.execute("""
                SELECT COLUMN_NAME 
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = 'users_branch'
                AND COLUMN_NAME IN ('mpesa_shortcode', 'mpesa_consumer_key', 'mpesa_consumer_secret', 'mpesa_passkey')
            """)
            existing_fields = [row[0] for row in cursor.fetchall()]
            print(f"Existing M-Pesa fields: {existing_fields}")
            return len(existing_fields) == 4
    except Exception as e:
        print(f"❌ Failed to check M-Pesa fields: {str(e)}")
        return False

def add_mpesa_fields():
    """Add M-Pesa fields to Branch model"""
    print("🔄 Adding M-Pesa fields...")
    try:
        with connection.cursor() as cursor:
            fields_to_add = [
                ('mpesa_shortcode', 'VARCHAR(10) NULL'),
                ('mpesa_consumer_key', 'VARCHAR(100) NULL'),
                ('mpesa_consumer_secret', 'VARCHAR(100) NULL'),
                ('mpesa_passkey', 'VARCHAR(100) NULL'),
            ]
            
            for field_name, field_type in fields_to_add:
                try:
                    cursor.execute(f"ALTER TABLE users_branch ADD COLUMN {field_name} {field_type}")
                    print(f"✅ Added field: {field_name}")
                except Exception as e:
                    if "Duplicate column name" in str(e):
                        print(f"✅ Field already exists: {field_name}")
                    else:
                        print(f"❌ Failed to add field {field_name}: {str(e)}")
                        return False
            
            print("✅ All M-Pesa fields added successfully!")
            return True
    except Exception as e:
        print(f"❌ Failed to add M-Pesa fields: {str(e)}")
        return False

def setup_mpesa_config():
    """Set up M-Pesa configuration"""
    print("🔄 Setting up M-Pesa configuration...")
    try:
        call_command('setup_production_mpesa', '--update-branches')
        print("✅ M-Pesa configuration set up successfully")
        return True
    except Exception as e:
        print(f"❌ Failed to set up M-Pesa configuration: {str(e)}")
        return False

def register_c2b_urls():
    """Register C2B URLs with M-Pesa"""
    print("🔄 Registering C2B URLs with M-Pesa...")
    try:
        # Get the main branch
        main_branch = Branch.objects.filter(is_main_branch=True).first()
        if not main_branch:
            main_branch = Branch.objects.first()
        
        if main_branch:
            service = BranchMpesaService(main_branch)
            result = service.register_c2b_urls()
            if result.get('success'):
                print("✅ C2B URLs registered successfully")
                print(f"Response: {result.get('response', {})}")
            else:
                print(f"⚠️ C2B URL registration failed: {result.get('error', 'Unknown error')}")
                print("You may need to register URLs manually in M-Pesa portal")
        else:
            print("⚠️ No branch found. Please create a branch first.")
        return True
    except Exception as e:
        print(f"⚠️ C2B URL registration failed: {str(e)}")
        print("You may need to register URLs manually in M-Pesa portal")
        return True  # Don't fail deployment for this

def deploy_mpesa_complete():
    """Complete M-Pesa deployment"""
    print("🚀 Complete M-Pesa Deployment")
    print("=" * 50)
    
    # Step 1: Check if M-Pesa fields exist
    if not check_mpesa_fields():
        print("🔄 M-Pesa fields missing, adding them...")
        if not add_mpesa_fields():
            print("❌ Failed to add M-Pesa fields")
            return False
    else:
        print("✅ M-Pesa fields already exist")
    
    # Step 2: Set up M-Pesa configuration
    if not setup_mpesa_config():
        print("❌ Failed to set up M-Pesa configuration")
        return False
    
    # Step 3: Register C2B URLs
    register_c2b_urls()
    
    # Step 4: Display callback URLs
    print("\n📋 IMPORTANT: Register these URLs in your M-Pesa portal:")
    print("   Confirmation URL: https://branchbusinessadvance.co.ke/payments/callback/confirmation/")
    print("   Validation URL: https://branchbusinessadvance.co.ke/payments/callback/validation/")
    print("   Response Type: Completed")
    
    print("\n🎉 Complete M-Pesa Deployment Successful!")
    print("=" * 50)
    print("📋 Next Steps:")
    print("1. Register the callback URLs in your M-Pesa portal")
    print("2. Test with a real payment to verify integration")
    print("3. Monitor the system for automatic payments")
    
    return True

if __name__ == "__main__":
    print("Complete M-Pesa Deployment Script")
    print("This script handles all deployment scenarios")
    
    # Run deployment
    success = deploy_mpesa_complete()
    
    if success:
        print("\n🏁 Complete deployment successful!")
        sys.exit(0)
    else:
        print("\n❌ Complete deployment failed!")
        sys.exit(1)
