"""
Data migration to fix amount_xof for existing donations.

This migration populates the amount_xof field for donations that have an amount
but amount_xof is 0 or null. This is needed for donations created before the
currency conversion system was implemented.
"""

from django.db import migrations
from django.db.models import Sum
from decimal import Decimal


def fix_donation_amounts(apps, schema_editor):
    """
    Forward migration: Fix amount_xof for all donations with amount > 0 but amount_xof = 0
    """
    # Get model (use historical version from migration)
    Donation = apps.get_model('appsponsor', 'Donation')
    
    # Exchange rates (must be copied here as migrations shouldn't import from app code)
    EXCHANGE_RATES = {
        'XOF': Decimal('1.0'),
        'EUR': Decimal('655.957'),
        'USD': Decimal('600.0'),
        'GBP': Decimal('750.0'),
        'CAD': Decimal('450.0'),
    }
    
    def to_xof(amount, currency):
        """Convert amount to XOF using exchange rates."""
        if not amount or not currency:
            return Decimal('0.00')
        
        amount = Decimal(str(amount))
        currency = currency.upper()
        
        if currency not in EXCHANGE_RATES:
            return Decimal('0.00')
        
        if currency == 'XOF':
            return amount
        
        # Convert to XOF
        rate = EXCHANGE_RATES[currency]
        return (amount * rate).quantize(Decimal('0.01'))
    
    # Find donations with amount > 0 but amount_xof = 0
    donations_to_fix = Donation.objects.filter(
        amount__gt=0,
        amount_xof=0
    )
    
    total_count = donations_to_fix.count()
    print(f'Found {total_count} donations to fix')
    
    if total_count == 0:
        print('No donations need fixing!')
        return
    
    # Fix each donation
    fixed_count = 0
    for donation in donations_to_fix:
        try:
            # Convert amount to XOF
            amount_xof = to_xof(donation.amount, donation.currency)
            
            # Update the donation
            donation.amount_xof = amount_xof
            donation.save(update_fields=['amount_xof'])
            
            fixed_count += 1
            
        except Exception as e:
            print(f'Error fixing donation {donation.id}: {str(e)}')
    
    print(f'Successfully fixed {fixed_count} out of {total_count} donations')
    
    # Calculate and display total approved amount
    total_approved = Donation.objects.filter(status='approved').aggregate(
        total=Sum('amount_xof')
    )['total'] or Decimal('0.00')
    
    print(f'Total approved amount: {int(total_approved):,} FCFA')


def reverse_fix(apps, schema_editor):
    """
    Reverse migration: Set amount_xof back to 0 for affected donations
    This is rarely needed but included for completeness
    """
    # Normally we wouldn't reverse a data fix, so this is a no-op
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('appsponsor', '0005_donation_amount_xof_donation_currency_and_more'),
    ]

    operations = [
        migrations.RunPython(fix_donation_amounts, reverse_fix),
    ]
