"""
Apply Access Control Fix to All Report Views
This script adds proper portfolio and branch filtering
"""
import re

# Read the file
with open('reports/views.py', 'r', encoding='utf-8') as f:
    content = f.content()

# Pattern 1: Replace direct Loan.objects.filter with get_filtered_loans_for_user
# But only in views that have selected_branch_id

patterns_to_fix = [
    # Pattern: loans_qs = Loan.objects.filter(status='active') followed by branch filter
    {
        'old': r"loans_qs = Loan\.objects\.filter\(status='active'\)\s+if selected_branch_id:\s+loans_qs = loans_qs\.filter\(borrower__branch_id=selected_branch_id\)",
        'new': "loans_qs = get_filtered_loans_for_user(request.user, selected_branch_id, base_queryset=Loan.objects.filter(status='active'))"
    },
    # Pattern: loans_qs = Loan.objects.filter(...) with branch filter on next lines
    {
        'old': r"loans_qs = Loan\.objects\.filter\(\s*is_deleted=False,\s*status='active'\s*\)\.select_related\([^)]+\)\s+# Apply branch filtering if provided\s+if selected_branch_id:\s+loans_qs = loans_qs\.filter\(borrower__branch_id=selected_branch_id\)",
        'new': "loans_qs = get_filtered_loans_for_user(request.user, selected_branch_id, base_queryset=Loan.objects.filter(is_deleted=False, status='active')).select_related('borrower', 'application', 'application__loan_product')"
    }
]

print("This script needs manual review of each view.")
print("The helper function get_filtered_loans_for_user() has been added.")
print("\nViews that need manual fixing:")
print("1. loans_due_today_report (line ~5420)")
print("2. missed_payments_report (line ~5500)")
print("3. enhanced_loans_due_report (line ~5620)")
print("4. enhanced_interest_income_report (line ~6145)")
print("5. overdue_loans_report (line ~6310)")
print("6. completed_loans_report (line ~6400)")
print("\nEach needs to replace:")
print("  Loan.objects.filter(...)")
print("  if selected_branch_id: loans_qs.filter(borrower__branch_id=...)")
print("\nWith:")
print("  get_filtered_loans_for_user(request.user, selected_branch_id, base_queryset=...)")
