#!/usr/bin/env python
"""
M-Pesa Deployment Script (No Migrations)
This script deploys M-Pesa integration without running migrations.
Use this when migrations are causing conflicts.
"""
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 payments.branch_mpesa_service import BranchMpesaService
from users.models import Branch

def deploy_mpesa_without_migrations():
    """Deploy M-Pesa integration without migrations"""
    print("🚀 M-Pesa Deployment (No Migrations)")
    print("=" * 50)
    
    try:
        # Step 1: Test database connection
        print("🔄 Testing database connection...")
        from django.db import connection
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
        print("✅ Database connection working")
        
        # Step 2: Set up production M-Pesa configuration
        print("🔄 Setting up production M-Pesa configuration...")
        call_command('setup_production_mpesa', '--update-branches')
        print("✅ Production M-Pesa configuration set up successfully")
        
        # Step 3: 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.")
        except Exception as e:
            print(f"⚠️ C2B URL registration failed: {str(e)}")
            print("You may need to register URLs manually in M-Pesa portal")
        
        # Step 4: Display callback URLs for manual registration
        print("\n📋 IMPORTANT: Register these URLs in your M-Pesa portal:")
        print("   Confirmation URL: https://branchbusinessadvance.co.ke/payments/mpesa/c2b/confirmation/")
        print("   Validation URL: https://branchbusinessadvance.co.ke/payments/mpesa/c2b/validation/")
        print("   Response Type: Completed")
        
        print("\n🎉 M-Pesa Integration Deployment Complete!")
        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
        
    except Exception as e:
        print(f"❌ Deployment failed: {str(e)}")
        return False

if __name__ == "__main__":
    print("M-Pesa Deployment Script (No Migrations)")
    print("This script will deploy M-Pesa integration without running migrations")
    print("Use this when migrations are causing conflicts")
    
    # Run deployment
    success = deploy_mpesa_without_migrations()
    
    if success:
        print("\n🏁 Deployment script completed successfully!")
        sys.exit(0)
    else:
        print("\n❌ Deployment script failed!")
        sys.exit(1)
