#!/usr/bin/env python
"""
Production Deployment Script for M-Pesa Integration
Run this on your cPanel server to deploy the M-Pesa integration
"""
import os
import sys
import django
import subprocess
import requests
import json

# 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 run_command(command, description):
    """Run a command and handle errors"""
    print(f"\n🔄 {description}...")
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True)
        if result.returncode == 0:
            print(f"✅ {description} completed successfully")
            if result.stdout:
                print(f"Output: {result.stdout}")
        else:
            print(f"❌ {description} failed")
            print(f"Error: {result.stderr}")
            return False
    except Exception as e:
        print(f"❌ {description} failed with exception: {str(e)}")
        return False
    return True

def deploy_mpesa_integration():
    """Deploy M-Pesa integration to production"""
    print("🚀 Starting M-Pesa Integration Deployment")
    print("=" * 50)
    
    # Step 1: Apply database migrations
    if not run_command("python manage.py migrate", "Applying database migrations"):
        return False
    
    # Step 2: Set up production M-Pesa configuration
    print("\n🔄 Setting up production M-Pesa configuration...")
    try:
        call_command('setup_production_mpesa', '--update-branches')
        print("✅ Production M-Pesa configuration set up successfully")
    except Exception as e:
        print(f"❌ Failed to set up M-Pesa configuration: {str(e)}")
        return False
    
    # Step 3: Register C2B URLs with M-Pesa
    print("\n🔄 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

if __name__ == "__main__":
    print("M-Pesa Production Deployment Script")
    print("This script will deploy the M-Pesa integration to production")
    
    # Ask for confirmation (handle non-interactive environments)
    try:
        confirm = input("\nDo you want to proceed with the deployment? (y/N): ")
        if confirm.lower() != 'y':
            print("Deployment cancelled.")
            sys.exit(0)
    except EOFError:
        print("\n⚠️ Running in non-interactive mode. Proceeding automatically...")
    
    # Run deployment
    success = deploy_mpesa_integration()
    
    if success:
        print("\n🏁 Deployment script completed successfully!")
    else:
        print("\n❌ Deployment script failed!")
        sys.exit(1)