"""
Django management command to fix and maintain registration fees data
"""
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.db.models import Sum, Count
from users.models import CustomUser
from reports.enhanced_models import RegistrationFeePayment
from reports.comprehensive_reports import ComprehensiveReportsService
from decimal import Decimal


class Command(BaseCommand):
    help = 'Fix and maintain registration fees data'

    def add_arguments(self, parser):
        parser.add_argument(
            '--fix-dates',
            action='store_true',
            help='Fix missing payment dates for paid registration fees',
        )
        parser.add_argument(
            '--verify',
            action='store_true',
            help='Verify registration fees calculations',
        )
        parser.add_argument(
            '--report',
            action='store_true',
            help='Generate comprehensive registration fees report',
        )
        parser.add_argument(
            '--branch',
            type=str,
            help='Filter by branch ID',
        )

    def handle(self, *args, **options):
        self.stdout.write(
            self.style.SUCCESS('=== Registration Fees Management Tool ===\n')
        )

        if options['fix_dates']:
            self.fix_missing_dates()

        if options['verify']:
            self.verify_calculations(options.get('branch'))

        if options['report']:
            self.generate_report(options.get('branch'))

        if not any([options['fix_dates'], options['verify'], options['report']]):
            self.show_help()

    def fix_missing_dates(self):
        """Fix missing payment dates for paid registration fees"""
        self.stdout.write('Fixing missing payment dates...')

        users_needing_dates = CustomUser.objects.filter(
            role='borrower',
            registration_fee_paid=True,
            registration_fee_amount__gt=0,
            registration_fee_payment_date__isnull=True
        )

        count = users_needing_dates.count()
        self.stdout.write(f'Found {count} users with missing payment dates')

        if count > 0:
            updated = 0
            for user in users_needing_dates:
                user.registration_fee_payment_date = user.created_at
                user.save(update_fields=['registration_fee_payment_date'])
                updated += 1

            self.stdout.write(
                self.style.SUCCESS(f'✅ Fixed payment dates for {updated} users')
            )
        else:
            self.stdout.write(
                self.style.SUCCESS('✅ All paid registration fees have payment dates')
            )

    def verify_calculations(self, branch_id=None):
        """Verify registration fees calculations"""
        self.stdout.write('Verifying registration fees calculations...')

        # Get data from CustomUser
        user_query = CustomUser.objects.filter(
            role='borrower',
            registration_fee_paid=True,
            registration_fee_amount__gt=0
        )
        
        if branch_id:
            user_query = user_query.filter(branch_id=branch_id)

        user_data = user_query.aggregate(
            total=Sum('registration_fee_amount'),
            count=Count('id')
        )

        # Get data from RegistrationFeePayment
        payment_query = RegistrationFeePayment.objects.all()
        if branch_id:
            payment_query = payment_query.filter(customer__branch_id=branch_id)

        payment_data = payment_query.aggregate(
            total=Sum('amount_paid'),
            count=Count('id')
        )

        # Test reports service
        reports_service = ComprehensiveReportsService()
        current_month = reports_service.get_registration_fees_report(branch_id=branch_id)
        all_time = reports_service.get_registration_fees_report(
            start_date=timezone.datetime(2020, 1, 1).date(),
            end_date=timezone.now().date(),
            branch_id=branch_id
        )

        # Display results
        self.stdout.write('\n--- Verification Results ---')
        self.stdout.write(f'CustomUser data: KES {user_data["total"] or 0:,.2f} from {user_data["count"]} users')
        self.stdout.write(f'RegistrationFeePayment data: KES {payment_data["total"] or 0:,.2f} from {payment_data["count"]} payments')
        
        combined_total = (user_data["total"] or 0) + (payment_data["total"] or 0)
        combined_count = (user_data["count"] or 0) + (payment_data["count"] or 0)
        self.stdout.write(f'Combined total: KES {combined_total:,.2f} from {combined_count} records')

        self.stdout.write(f'\nReports service - Current month: KES {current_month["summary"]["total_registration_income"]:,.2f}')
        self.stdout.write(f'Reports service - All time: KES {all_time["summary"]["total_registration_income"]:,.2f}')

        # Validation
        if abs(float(all_time["summary"]["total_registration_income"]) - float(combined_total)) < 0.01:
            self.stdout.write(self.style.SUCCESS('✅ Calculations are correct!'))
        else:
            self.stdout.write(self.style.ERROR('❌ Calculation mismatch detected!'))

    def generate_report(self, branch_id=None):
        """Generate comprehensive registration fees report"""
        self.stdout.write('Generating comprehensive report...')

        reports_service = ComprehensiveReportsService()
        
        # Current month report
        current_month = reports_service.get_registration_fees_report(branch_id=branch_id)
        
        # All time report
        all_time = reports_service.get_registration_fees_report(
            start_date=timezone.datetime(2020, 1, 1).date(),
            end_date=timezone.now().date(),
            branch_id=branch_id
        )

        # Additional analytics
        all_users = CustomUser.objects.filter(role='borrower')
        if branch_id:
            all_users = all_users.filter(branch_id=branch_id)

        users_with_fees = all_users.filter(registration_fee_amount__gt=0).count()
        paid_users = all_users.filter(
            registration_fee_paid=True,
            registration_fee_amount__gt=0
        ).count()
        unpaid_users = users_with_fees - paid_users
        payment_rate = (paid_users / users_with_fees * 100) if users_with_fees > 0 else 0

        # Display report
        self.stdout.write('\n=== REGISTRATION FEES COMPREHENSIVE REPORT ===')
        
        self.stdout.write(f'\n📊 CURRENT MONTH ({timezone.now().strftime("%B %Y")})')
        self.stdout.write(f'   Total Income: KES {current_month["summary"]["total_registration_income"]:,.2f}')
        self.stdout.write(f'   Total Registrations: {current_month["summary"]["total_registrations"]}')
        self.stdout.write(f'   Average Fee: KES {current_month["summary"]["average_registration_fee"]:,.2f}')

        self.stdout.write(f'\n📈 ALL TIME')
        self.stdout.write(f'   Total Income: KES {all_time["summary"]["total_registration_income"]:,.2f}')
        self.stdout.write(f'   Total Registrations: {all_time["summary"]["total_registrations"]}')
        self.stdout.write(f'   Average Fee: KES {all_time["summary"]["average_registration_fee"]:,.2f}')

        self.stdout.write(f'\n👥 CLIENT OVERVIEW')
        self.stdout.write(f'   Total Clients: {all_users.count()}')
        self.stdout.write(f'   Clients with Fees: {users_with_fees}')
        self.stdout.write(f'   Paid Clients: {paid_users}')
        self.stdout.write(f'   Unpaid Clients: {unpaid_users}')
        self.stdout.write(f'   Payment Rate: {payment_rate:.1f}%')

        if branch_id:
            self.stdout.write(f'\n🏢 BRANCH FILTER: {branch_id}')

        # Show recent fees if available
        if all_time.get('fees'):
            self.stdout.write(f'\n💰 RECENT FEES (Last 5)')
            for i, fee in enumerate(all_time['fees'][:5]):
                self.stdout.write(f'   {i+1}. {fee["customer_name"]}: KES {fee["amount"]} ({fee["source"]})')

        self.stdout.write('\n' + '='*50)

    def show_help(self):
        """Show help information"""
        self.stdout.write('Available options:')
        self.stdout.write('  --fix-dates    Fix missing payment dates')
        self.stdout.write('  --verify       Verify calculations')
        self.stdout.write('  --report       Generate comprehensive report')
        self.stdout.write('  --branch ID    Filter by branch ID')
        self.stdout.write('\nExamples:')
        self.stdout.write('  python manage.py fix_registration_fees --verify')
        self.stdout.write('  python manage.py fix_registration_fees --fix-dates --verify')
        self.stdout.write('  python manage.py fix_registration_fees --report --branch 123')