#!/usr/bin/env python
"""
Add some current month registration fee data for testing
"""
import os
import sys
import django

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

from django.utils import timezone
from users.models import CustomUser
from reports.enhanced_models import RegistrationFee, RegistrationFeePayment
from decimal import Decimal

def add_current_month_test_data():
    """Add some test registration fee data for the current month"""
    
    print("=== Adding Current Month Registration Fee Test Data ===\n")
    
    current_month = timezone.now().replace(day=1, hour=0, minute=0, second=0, microsecond=0)
    
    # 1. Update existing unpaid user to be paid this month
    try:
        unpaid_user = CustomUser.objects.filter(
            role='borrower',
            registration_fee_paid=False,
            registration_fee_amount__gt=0
        ).first()
        
        if unpaid_user:
            unpaid_user.registration_fee_paid = True
            unpaid_user.registration_fee_payment_date = timezone.now()
            unpaid_user.registration_fee_payment_method = 'mpesa'
            unpaid_user.registration_fee_receipt_number = 'REC-001-OCT'
            unpaid_user.save()
            
            print(f"✅ Updated {unpaid_user.get_full_name()} - marked as paid this month")
            print(f"   Amount: KES {unpaid_user.registration_fee_amount}")
            print(f"   Payment Date: {unpaid_user.registration_fee_payment_date}")
        else:
            print("ℹ️  No unpaid users found to update")
    
    except Exception as e:
        print(f"❌ Error updating existing user: {e}")
    
    # 2. Create a new test user with current month registration
    try:
        # Check if test user already exists
        test_user, created = CustomUser.objects.get_or_create(
            username='test_current_month_user',
            defaults={
                'first_name': 'Current',
                'last_name': 'Month User',
                'email': 'current.month@test.com',
                'phone_number': '+254700000999',
                'role': 'borrower',
                'registration_fee_amount': Decimal('100.00'),
                'registration_fee_paid': True,
                'registration_fee_payment_date': timezone.now(),
                'registration_fee_payment_method': 'cash',
                'registration_fee_receipt_number': 'REC-002-OCT',
            }
        )
        
        if created:
            print(f"✅ Created new test user: {test_user.get_full_name()}")
            print(f"   Amount: KES {test_user.registration_fee_amount}")
            print(f"   Payment Date: {test_user.registration_fee_payment_date}")
        else:
            # Update existing test user
            test_user.registration_fee_paid = True
            test_user.registration_fee_payment_date = timezone.now()
            test_user.save()
            print(f"✅ Updated existing test user: {test_user.get_full_name()}")
    
    except Exception as e:
        print(f"❌ Error creating test user: {e}")
    
    # 3. Create a registration fee and payment record
    try:
        # Create or get a registration fee
        reg_fee, created = RegistrationFee.objects.get_or_create(
            product_type='boost',
            fee_name='Boost Registration Fee',
            defaults={
                'amount': Decimal('150.00'),
                'description': 'Registration fee for Boost product',
                'is_active': True,
            }
        )
        
        if created:
            print(f"✅ Created registration fee: {reg_fee.fee_name}")
        
        # Find a user to create payment for
        payment_user = CustomUser.objects.filter(role='borrower').first()
        
        if payment_user:
            # Create payment record
            payment, created = RegistrationFeePayment.objects.get_or_create(
                customer=payment_user,
                registration_fee=reg_fee,
                defaults={
                    'amount_paid': reg_fee.amount,
                    'payment_method': 'mpesa',
                    'payment_date': timezone.now(),
                    'transaction_reference': 'MPESA123456789',
                    'payment_notes': 'Test payment for current month',
                }
            )
            
            if created:
                print(f"✅ Created payment record: {payment.receipt_number}")
                print(f"   Customer: {payment.customer.get_full_name()}")
                print(f"   Amount: KES {payment.amount_paid}")
                print(f"   Date: {payment.payment_date}")
            else:
                print(f"ℹ️  Payment record already exists: {payment.receipt_number}")
    
    except Exception as e:
        print(f"❌ Error creating registration fee payment: {e}")
    
    # 4. Test the calculation
    print("\n=== Testing Updated Calculation ===")
    
    from reports.comprehensive_reports import ComprehensiveReportsService
    reports_service = ComprehensiveReportsService()
    
    current_month_report = reports_service.get_registration_fees_report()
    print(f"Current month total income: KES {current_month_report['summary']['total_registration_income']:,.2f}")
    print(f"Current month total registrations: {current_month_report['summary']['total_registrations']}")
    
    if current_month_report['summary']['total_registration_income'] > 0:
        print("✅ SUCCESS: Current month now shows registration fee income!")
    else:
        print("⚠️  Still showing 0 - may need to check date filtering logic")
    
    print("\n=== Summary ===")
    print("The registration fees system has been updated with current month data.")
    print("You should now see non-zero values in the Reports & Statements dashboard.")
    print("Visit the dashboard to verify the changes.")

if __name__ == "__main__":
    add_current_month_test_data()