#!/usr/bin/env python
"""
Deploy Manual Payment Matching Feature

This script helps deploy the manual payment matching feature to production.
No database migrations are needed - only code changes.
"""

import os
import sys
import django

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

def main():
    print("="*70)
    print("DEPLOYING MANUAL PAYMENT MATCHING FEATURE")
    print("="*70)
    print()
    
    print("✓ This feature adds the ability to manually match unmatched M-Pesa")
    print("  payments to borrowers from the callbacks page.")
    print()
    
    print("Files Modified:")
    print("  1. payments/views.py - Added manual_match_payment view")
    print("  2. payments/urls.py - Added manual-match URL route")
    print("  3. templates/payments/callbacks.html - Added match button and modal")
    print()
    
    print("No database migrations required!")
    print()
    
    print("="*70)
    print("DEPLOYMENT STEPS FOR CPANEL")
    print("="*70)
    print()
    
    print("1. Upload the following files to your cPanel:")
    print("   - payments/views.py")
    print("   - payments/urls.py")
    print("   - templates/payments/callbacks.html")
    print()
    
    print("2. Restart your application:")
    print("   - In cPanel, go to 'Setup Python App'")
    print("   - Click 'Restart' button for your application")
    print()
    
    print("3. Test the feature:")
    print("   - Go to: https://branchbusinessadvance.co.ke/payments/callbacks/")
    print("   - Find a payment marked '⚠️ Not matched'")
    print("   - Click '👤 Match Payer' button")
    print("   - Select a borrower and submit")
    print()
    
    print("="*70)
    print("FEATURE USAGE")
    print("="*70)
    print()
    
    print("For unmatched payments (marked with ⚠️ Not matched):")
    print("  1. Click the '👤 Match Payer' button")
    print("  2. Search for the borrower by name, ID, or phone")
    print("  3. Select the correct borrower")
    print("  4. Click 'Match & Process Payment'")
    print()
    
    print("The system will:")
    print("  ✓ Link the payment to the selected borrower")
    print("  ✓ Update the bill reference number")
    print("  ✓ Automatically process the payment")
    print("  ✓ Create a repayment if the borrower has an active loan")
    print("  ✓ Log the manual match with your admin username")
    print()
    
    print("="*70)
    print("TESTING CHECKLIST")
    print("="*70)
    print()
    
    from payments.models import MpesaCallback
    from loans.models import MpesaTransaction
    from django.contrib.auth import get_user_model
    
    User = get_user_model()
    
    # Check for unmatched payments
    unmatched_count = MpesaTransaction.objects.filter(
        borrower__isnull=True,
        status__in=['pending', 'confirmed', 'validated']
    ).count()
    
    print(f"[ ] Found {unmatched_count} unmatched payment(s) to test with")
    
    # Check for active borrowers
    borrower_count = User.objects.filter(role='borrower', is_active=True).count()
    print(f"[ ] Found {borrower_count} active borrower(s) available for matching")
    
    # Check callbacks page access
    print("[ ] Access callbacks page: /payments/callbacks/")
    print("[ ] Verify 'Match Payer' button appears for unmatched payments")
    print("[ ] Click button and verify modal opens")
    print("[ ] Verify borrower dropdown is searchable")
    print("[ ] Select a borrower and submit")
    print("[ ] Verify success message appears")
    print("[ ] Verify payment is now matched to the borrower")
    print("[ ] Verify repayment was created (if borrower has active loan)")
    print()
    
    print("="*70)
    print("DEPLOYMENT COMPLETE!")
    print("="*70)
    print()
    
    print("📖 For detailed usage instructions, see:")
    print("   MANUAL_PAYMENT_MATCHING_GUIDE.md")
    print()

if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        print(f"\n❌ Error: {str(e)}")
        sys.exit(1)
