import re                                                                                             
with open('finance/views.py', 'r') as f:
    content = f.read()

# Find PaymentCreateView's form_valid method (around line 341)
# We'll use a more flexible pattern

old_pattern = r'(class PaymentCreateView.*?def form_valid\(self, form\):)(.*?)(return super\(\)\.form_valid\(form\))'

def replacement(match):
    prefix = match.group(1)
    suffix = match.group(3)

    new_body = '''
        # Check for duplicate payment (same invoice + amount within 5 minutes)
        from datetime import timedelta
        invoice = form.instance.invoice
        amount = form.cleaned_data['amount']
        payment_date = form.cleaned_data['payment_date']
   
        five_min_ago = timezone.now() - timedelta(minutes=5)
        duplicate = Payment.objects.filter(
            invoice=invoice,
            amount=amount,
            payment_date=payment_date,
            created_at__gte=five_min_ago
        ).exists()
   
        if duplicate:
            messages.warning(self.request, 'A payment with these exact details was already recorded in   the last 5 minutes.')
            return redirect('finance:payment_list')
   
        # Normal processing
        form.instance.student = form.instance.invoice.student
        form.instance.received_by = self.request.user
        form.instance.payment_number = f"PAY-{timezone.now().year}-{Payment.objects.count() + 1:04d}"
   
        messages.success(self.request, 'Payment recorded successfully!')
  '''
    return prefix + new_body + suffix

# Find PaymentCreateView class and its form_valid
new_content = re.sub(old_pattern, replacement, content, flags=re.DOTALL)

if new_content != content:
    with open('finance/views.py', 'w') as f:
        f.write(new_content)
    print("✓ views.py patched successfully")
else:
    print("WARNING: No changes made")