"""
Setup and fix M-Pesa configuration for both branches
This script ensures both branches have proper M-Pesa credentials
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from users.models import Branch

print("=" * 80)
print("M-PESA BRANCH CONFIGURATION SETUP")
print("=" * 80)

# Main Branch Configuration
print("\n1. Configuring MAIN BRANCH...")
print("-" * 80)

main_branch = Branch.objects.filter(is_main_branch=True).first()
if not main_branch:
    print("⚠ No main branch found! Please create one first.")
else:
    print(f"Found Main Branch: {main_branch.name}")
    
    # Set Main branch M-Pesa configuration
    main_branch.mpesa_shortcode = '4086675'
    main_branch.mpesa_consumer_key = 'L00rQYgBd5WrsGYI4a0Agb9P8SSCgaYGA3uF0Dme0IgKsAN5'
    main_branch.mpesa_consumer_secret = 'nuHpJxybEO0eh3qAlpckBFPzveHEV3A6LUNOl5gUwqIU53I03aIGY4VM1vVHRJDC'
    main_branch.save()
    
    print(f"✓ Updated Main Branch:")
    print(f"  - Shortcode: {main_branch.mpesa_shortcode}")
    print(f"  - Consumer Key: {main_branch.mpesa_consumer_key[:30]}...")
    print(f"  - Consumer Secret: {main_branch.mpesa_consumer_secret[:30]}...")

# Juja Branch Configuration
print("\n2. Configuring JUJA OFFICE...")
print("-" * 80)

juja_branch = Branch.objects.filter(code='002').first()
if not juja_branch:
    print("⚠ No Juja branch found (code 002)! Creating...")
    juja_branch = Branch.objects.create(
        name='JUJA OFFICE',
        code='002',
        address='5477',
        phone_number='+254757206664',
        is_main_branch=False,
        is_active=True
    )
    print(f"✓ Created Juja Branch: {juja_branch.name}")
else:
    print(f"Found Juja Branch: {juja_branch.name}")

# Set Juja branch M-Pesa configuration
juja_branch.mpesa_shortcode = '4159523'
juja_branch.mpesa_consumer_key = '9mD1A3H1qw5grqdqkZ4X1G9zbNxioydHXL5An4nkUGRlNRKr'
juja_branch.mpesa_consumer_secret = 'C2dqBSaGFUIporfYYuyhQgnfPEqLvCS3GvfAJ91ENkXI2bhqptlVXAqMelsEpLQR'
juja_branch.save()

print(f"✓ Updated Juja Branch:")
print(f"  - Shortcode: {juja_branch.mpesa_shortcode}")
print(f"  - Consumer Key: {juja_branch.mpesa_consumer_key[:30]}...")
print(f"  - Consumer Secret: {juja_branch.mpesa_consumer_secret[:30]}...")

print("\n" + "=" * 80)
print("CONFIGURATION COMPLETE")
print("=" * 80)

print("\nIMPORTANT NEXT STEPS:")
print("-" * 80)
print("1. REGISTER CALLBACK URLs WITH SAFARICOM")
print("   You need to register these URLs for BOTH paybills (4086675 and 4159523):")
print("")
print("   Validation URL:")
print("   https://branchbusinessadvance.co.ke/payments/callback/validation/")
print("")
print("   Confirmation URL:")
print("   https://branchbusinessadvance.co.ke/payments/callback/confirmation/")
print("")
print("2. HOW TO REGISTER:")
print("   - Log into Safaricom M-Pesa portal")
print("   - Navigate to C2B URLs section")
print("   - Register the URLs for EACH shortcode (4086675 and 4159523)")
print("   - Test with a small payment")
print("")
print("3. VERIFY SETUP:")
print("   - Make a test payment to shortcode 4086675 (Main Branch)")
print("   - Make a test payment to shortcode 4159523 (Juja Branch)")
print("   - Check the admin panel to see if callbacks are received")
print("")
print("4. TROUBLESHOOTING:")
print("   If Main branch still doesn't receive payments:")
print("   - Verify the paybill 4086675 is active")
print("   - Check if callback URLs are whitelisted on Safaricom portal")
print("   - Review the callback logs in the admin panel")
print("   - Test with Safaricom sandbox environment first")

print("\n✓ Branch configurations saved successfully!")
