import os

file_path = 'core/views.py'
search_text = "@login_required\ndef expense_categories_view(request): return render(request, 'core/expense_categories.html')"
replace_text = """@login_required
def expense_categories_view(request):
    if request.method == 'POST':
        category_id = request.POST.get('category_id')
        name_en = request.POST.get('name_en')
        name_ar = request.POST.get('name_ar')
        description = request.POST.get('description')
        
        if category_id:
            # Update existing category
            category = get_object_or_404(ExpenseCategory, pk=category_id)
            category.name_en = name_en
            category.name_ar = name_ar
            category.description = description
            category.save()
            messages.success(request, _('Expense category updated successfully.'))
        else:
            # Create new category
            ExpenseCategory.objects.create(
                name_en=name_en,
                name_ar=name_ar,
                description=description
            )
            messages.success(request, _('Expense category added successfully.'))
        return redirect('expense_categories')

    categories = ExpenseCategory.objects.all().order_by('-id')
    return render(request, 'core/expense_categories.html', {'categories': categories})"""

with open(file_path, 'r') as f:
    content = f.read()

if search_text in content:
    new_content = content.replace(search_text, replace_text)
    with open(file_path, 'w') as f:
        f.write(new_content)
    print("Successfully patched expense_categories_view")
else:
    print("Could not find the target function to replace")
