#!/usr/bin/env python
"""
Safely identify and delete duplicate repayments.

DUPLICATE DETECTION LOGIC:
--------------------------
Two repayments are considered duplicates if they have:
1. Same loan_id
2. Same amount
3. Same payment_method
4. Payment dates within 5 seconds of each other (to catch rapid double-submits)

SAFETY MEASURES:
----------------
1. Dry-run mode by default (shows what would be deleted without actually deleting)
2. Groups duplicates and keeps the FIRST one (oldest by ID)
3. Shows detailed preview before any deletion
4. Confirms with user before proceeding
5. Deletes associated receipts first (to avoid FK constraint errors)
6. Recalculates loan amount_paid after deletion
"""
import os
import django
from decimal import Decimal
from datetime import timedelta

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

from django.db import transaction
from django.db.models import Count, Q
from loans.models import Loan, Repayment
from utils.models import Receipt

def find_duplicate_repayments():
    """
    Find groups of duplicate repayments.
    Returns a list of duplicate groups, where each group is a list of repayment IDs.
    """
    print("\n" + "="*80)
    print("SEARCHING FOR DUPLICATE REPAYMENTS")
    print("="*80)
    
    all_repayments = Repayment.objects.all().order_by('loan_id', 'payment_date', 'id')
    
    duplicate_groups = []
    processed_ids = set()
    
    for repayment in all_repayments:
        if repayment.id in processed_ids:
            continue
        
        # Find potential duplicates for this repayment
        # Same loan, same amount, same method, payment date within 5 seconds
        time_window_start = repayment.payment_date - timedelta(seconds=5)
        time_window_end = repayment.payment_date + timedelta(seconds=5)
        
        duplicates = Repayment.objects.filter(
            loan=repayment.loan,
            amount=repayment.amount,
            payment_method=repayment.payment_method,
            payment_date__gte=time_window_start,
            payment_date__lte=time_window_end
        ).order_by('id')
        
        # If we found more than 1 (including the original), it's a duplicate group
        if duplicates.count() > 1:
            duplicate_ids = list(duplicates.values_list('id', flat=True))
            
            # Only add if we haven't processed this group yet
            if not any(dup_id in processed_ids for dup_id in duplicate_ids):
                duplicate_groups.append(duplicate_ids)
                processed_ids.update(duplicate_ids)
    
    return duplicate_groups

def preview_duplicates(duplicate_groups):
    """Show what would be deleted"""
    if not duplicate_groups:
        print("\n✓ No duplicate repayments found!")
        return False
    
    print(f"\n📊 Found {len(duplicate_groups)} duplicate groups:")
    print("="*80)
    
    total_to_delete = 0
    
    for idx, group in enumerate(duplicate_groups, 1):
        repayments = Repayment.objects.filter(id__in=group).order_by('id')
        first = repayments.first()
        
        print(f"\nGroup {idx}:")
        print(f"  Loan: {first.loan.loan_number}")
        print(f"  Borrower: {first.loan.borrower.get_full_name()}")
        print(f"  Amount: KES {first.amount:,.2f}")
        print(f"  Payment Method: {first.get_payment_method_display()}")
        print(f"  Count: {len(group)} duplicates")
        print(f"  Action: Keep FIRST (ID: {group[0]}), Delete {len(group)-1} others")
        
        print(f"\n  Details:")
        for rep in repayments:
            keep_or_delete = "KEEP ✓" if rep.id == group[0] else "DELETE ✗"
            print(f"    {keep_or_delete} - ID: {rep.id}, Receipt: {rep.receipt_number}, "
                  f"Date: {rep.payment_date.strftime('%Y-%m-%d %H:%M:%S')}")
        
        total_to_delete += len(group) - 1
    
    print("\n" + "="*80)
    print(f"SUMMARY: {total_to_delete} duplicate repayments will be deleted")
    print(f"         {len(duplicate_groups)} repayments will be kept (one per group)")
    print("="*80)
    
    return True

def delete_duplicates(duplicate_groups):
    """Delete duplicate repayments (keeping the first in each group)"""
    if not duplicate_groups:
        return
    
    print("\n⚠️  DELETION IN PROGRESS")
    print("="*80)
    
    total_deleted = 0
    total_receipts_deleted = 0
    affected_loans = set()
    
    for idx, group in enumerate(duplicate_groups, 1):
        # Keep the first (oldest by ID), delete the rest
        to_keep = group[0]
        to_delete = group[1:]
        
        print(f"\nProcessing Group {idx}...")
        
        for rep_id in to_delete:
            try:
                repayment = Repayment.objects.get(id=rep_id)
                affected_loans.add(repayment.loan.id)
                
                # Delete associated receipts first
                receipts_deleted = Receipt.objects.filter(repayment=repayment).delete()[0]
                total_receipts_deleted += receipts_deleted
                
                # Delete the repayment
                repayment.delete()
                total_deleted += 1
                
                print(f"  ✓ Deleted repayment ID {rep_id} (and {receipts_deleted} receipt(s))")
                
            except Exception as e:
                print(f"  ✗ Error deleting repayment ID {rep_id}: {e}")
    
    # Recalculate amount_paid for affected loans
    print(f"\n📊 Recalculating totals for {len(affected_loans)} affected loans...")
    for loan_id in affected_loans:
        try:
            loan = Loan.objects.get(id=loan_id)
            
            # Recalculate amount_paid from remaining repayments
            from django.db.models import Sum
            total_paid = loan.repayments.aggregate(
                total=Sum('amount')
            )['total'] or Decimal('0.00')
            
            loan._amount_paid_cache = total_paid
            loan.save(update_fields=['_amount_paid_cache'])
            
            print(f"  ✓ Updated loan {loan.loan_number}: KES {total_paid:,.2f} paid")
            
        except Exception as e:
            print(f"  ✗ Error updating loan {loan_id}: {e}")
    
    print("\n" + "="*80)
    print(f"✓ DELETION COMPLETE")
    print(f"  Repayments deleted: {total_deleted}")
    print(f"  Receipts deleted: {total_receipts_deleted}")
    print(f"  Loans updated: {len(affected_loans)}")
    print("="*80)

def main():
    print("\n" + "="*80)
    print("DUPLICATE REPAYMENT CLEANUP TOOL")
    print("="*80)
    
    # Step 1: Find duplicates
    duplicate_groups = find_duplicate_repayments()
    
    if not duplicate_groups:
        print("\n✅ No duplicates found - database is clean!")
        return
    
    # Step 2: Preview what would be deleted
    has_duplicates = preview_duplicates(duplicate_groups)
    
    if not has_duplicates:
        return
    
    # Step 3: 5-second countdown with Ctrl+C option
    print("\n" + "="*80)
    print("⚠️  FINAL WARNING ⚠️")
    print("="*80)
    print("This will permanently delete duplicate repayments.")
    print("Press Ctrl+C now to cancel, or wait 5 seconds to proceed...\n")
    
    import time
    import sys
    try:
        for i in range(5, 0, -1):
            print(f"  {i}...", end='', flush=True)
            time.sleep(1)
        print("\n")
    except KeyboardInterrupt:
        print("\n\n✗ Cancelled by user. No data was deleted.")
        sys.exit(0)
    
    # Step 4: Proceed with deletion
    print("🚀 Starting deletion...")
    
    try:
        with transaction.atomic():
            delete_duplicates(duplicate_groups)
            print("\n✅ All changes committed to database!")
    except Exception as e:
        print(f"\n✗ ERROR: Deletion failed and was rolled back: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

if __name__ == '__main__':
    import sys
    main()
