import os
import decimal
from django.db import transaction
from django.db.models import Sum

file_path = 'core/views.py'
with open(file_path, 'r') as f:
    content = f.read()

# 1. Update invoice_list
old_invoice_list = """@login_required
def invoice_list(request):
    sales = Sale.objects.all().order_by('-created_at')
    paginator = Paginator(sales, 25)
    return render(request, 'core/invoices.html', {
        'sales': paginator.get_page(request.GET.get('page')),
        'customers': Customer.objects.all(),
        'site_settings': SystemSetting.objects.first()
    })"""

new_invoice_list = """@login_required
def invoice_list(request):
    sales = Sale.objects.all().order_by('-created_at')
    paginator = Paginator(sales, 25)
    return render(request, 'core/invoices.html', {
        'sales': paginator.get_page(request.GET.get('page')),
        'customers': Customer.objects.all(),
        'site_settings': SystemSetting.objects.first(),
        'payment_methods': PaymentMethod.objects.filter(is_active=True)
    })"""
    
if old_invoice_list in content:
    content = content.replace(old_invoice_list, new_invoice_list)
else:
    print("Could not find old_invoice_list")

# 2. Update purchases
old_purchases = """@login_required
def purchases(request):
    purchases = Purchase.objects.all().order_by('-created_at')
    paginator = Paginator(purchases, 25)
    return render(request, 'core/purchases.html', {'purchases': paginator.get_page(request.GET.get('page'))})"""

new_purchases = """@login_required
def purchases(request):
    purchases = Purchase.objects.all().order_by('-created_at')
    paginator = Paginator(purchases, 25)
    return render(request, 'core/purchases.html', {
        'purchases': paginator.get_page(request.GET.get('page')),
        'payment_methods': PaymentMethod.objects.filter(is_active=True)
    })"""
    
if old_purchases in content:
    content = content.replace(old_purchases, new_purchases)
else:
    print("Could not find old_purchases")

# 3. Update invoice_detail
old_invoice_detail = """@login_required
def invoice_detail(request, pk):
    sale = get_object_or_404(Sale, pk=pk)
    settings = SystemSetting.objects.first()
    amount_in_words = number_to_words_en(sale.total_amount)
    return render(request, 'core/invoice_detail.html', {
        'sale': sale,
        'settings': settings,
        'amount_in_words': amount_in_words
    })"""

new_invoice_detail = """@login_required
def invoice_detail(request, pk):
    sale = get_object_or_404(Sale, pk=pk)
    settings = SystemSetting.objects.first()
    amount_in_words = number_to_words_en(sale.total_amount)
    return render(request, 'core/invoice_detail.html', {
        'sale': sale,
        'settings': settings,
        'amount_in_words': amount_in_words,
        'payment_methods': PaymentMethod.objects.filter(is_active=True)
    })"""

if old_invoice_detail in content:
    content = content.replace(old_invoice_detail, new_invoice_detail)
else:
    print("Could not find old_invoice_detail")

# 4. Update purchase_detail
old_purchase_detail = """@login_required
def purchase_detail(request, pk):
    purchase = get_object_or_404(Purchase, pk=pk)
    settings = SystemSetting.objects.first()
    return render(request, 'core/purchase_detail.html', {
        'purchase': purchase,
        'settings': settings
    })"""

new_purchase_detail = """@login_required
def purchase_detail(request, pk):
    purchase = get_object_or_404(Purchase, pk=pk)
    settings = SystemSetting.objects.first()
    return render(request, 'core/purchase_detail.html', {
        'purchase': purchase,
        'settings': settings,
        'payment_methods': PaymentMethod.objects.filter(is_active=True)
    })"""

if old_purchase_detail in content:
    content = content.replace(old_purchase_detail, new_purchase_detail)
else:
    print("Could not find old_purchase_detail")

# 5. Replace add_sale_payment stub
old_add_sale_payment = """@login_required
def add_sale_payment(request, pk): return redirect('invoices')"""

new_add_sale_payment = """@login_required
def add_sale_payment(request, pk):
    sale = get_object_or_404(Sale, pk=pk)
    if request.method == 'POST':
        try:
            amount = decimal.Decimal(request.POST.get('amount', 0))
            payment_method_id = request.POST.get('payment_method_id')
            notes = request.POST.get('notes', '')

            if amount > 0:
                with transaction.atomic():
                    SalePayment.objects.create(
                        sale=sale,
                        amount=amount,
                        payment_method_id=payment_method_id,
                        created_by=request.user,
                        notes=notes
                    )
                    
                    # Recalculate totals
                    total_paid = SalePayment.objects.filter(sale=sale).aggregate(Sum('amount'))['amount__sum'] or 0
                    sale.paid_amount = total_paid
                    sale.balance_due = sale.total_amount - total_paid
                    
                    if sale.balance_due <= 0:
                        sale.status = 'paid'
                    elif sale.paid_amount > 0:
                        sale.status = 'partial'
                    else:
                        sale.status = 'unpaid'
                    
                    sale.save()
                    messages.success(request, f"Payment of {amount} recorded successfully.")
            else:
                messages.error(request, "Amount must be greater than 0.")
        except Exception as e:
            messages.error(request, f"Error recording payment: {e}")
            
    return redirect('invoices')"""

if old_add_sale_payment in content:
    content = content.replace(old_add_sale_payment, new_add_sale_payment)
else:
    print("Could not find old_add_sale_payment")

# 6. Replace add_purchase_payment stub
old_add_purchase_payment = """@login_required
def add_purchase_payment(request, pk): return redirect('purchases')"""

new_add_purchase_payment = """@login_required
def add_purchase_payment(request, pk):
    purchase = get_object_or_404(Purchase, pk=pk)
    if request.method == 'POST':
        try:
            amount = decimal.Decimal(request.POST.get('amount', 0))
            payment_method_id = request.POST.get('payment_method_id')
            notes = request.POST.get('notes', '')

            if amount > 0:
                with transaction.atomic():
                    PurchasePayment.objects.create(
                        purchase=purchase,
                        amount=amount,
                        payment_method_id=payment_method_id,
                        created_by=request.user,
                        notes=notes
                    )
                    
                    # Recalculate totals
                    total_paid = PurchasePayment.objects.filter(purchase=purchase).aggregate(Sum('amount'))['amount__sum'] or 0
                    purchase.paid_amount = total_paid
                    purchase.balance_due = purchase.total_amount - total_paid
                    
                    if purchase.balance_due <= 0:
                        purchase.status = 'paid'
                    elif purchase.paid_amount > 0:
                        purchase.status = 'partial'
                    else:
                        purchase.status = 'unpaid'
                    
                    purchase.save()
                    messages.success(request, f"Payment of {amount} recorded successfully.")
            else:
                messages.error(request, "Amount must be greater than 0.")
        except Exception as e:
             messages.error(request, f"Error recording payment: {e}")

    return redirect('purchases')"""

if old_add_purchase_payment in content:
    content = content.replace(old_add_purchase_payment, new_add_purchase_payment)
else:
    print("Could not find old_add_purchase_payment")

with open(file_path, 'w') as f:
    f.write(content)
