"""
Script to add missing view functions to reports/views.py
"""

def add_missing_views():
    """Add missing view functions to reports/views.py"""
    
    missing_views_code = '''

# Legacy report views (keeping for compatibility)
@login_required
def borrower_reports(request):
    """Borrower reports with branch filtering"""
    user = request.user
    
    # Apply branch filtering
    branch_filter = {}
    if not user.is_superuser and hasattr(user, 'branch') and user.branch:
        branch_filter = {'branch': user.branch}
    
    # Get borrower statistics
    borrowers = CustomUser.objects.filter(role='borrower', **branch_filter)
    
    # Basic statistics
    total_borrowers = borrowers.count()
    active_borrowers = borrowers.filter(is_active=True).count()
    inactive_borrowers = borrowers.filter(is_active=False).count()
    
    # Borrowers with loans
    borrowers_with_loans = borrowers.filter(loans__isnull=False).distinct().count()
    
    context = {
        'total_borrowers': total_borrowers,
        'active_borrowers': active_borrowers,
        'inactive_borrowers': inactive_borrowers,
        'borrowers_with_loans': borrowers_with_loans,
        'borrowers': borrowers[:20],  # Show first 20 for display
    }
    
    return render(request, 'reports/borrower_reports.html', context)

@login_required
def loan_reports(request):
    """Loan reports with branch filtering"""
    user = request.user
    
    # Apply branch filtering
    branch_filter = {}
    if not user.is_superuser and hasattr(user, 'branch') and user.branch:
        branch_filter = {'borrower__branch': user.branch}
    
    # Get loan statistics
    loans = Loan.objects.filter(**branch_filter)
    
    # Basic statistics
    total_loans = loans.count()
    active_loans = loans.filter(status='active').count()
    completed_loans = loans.filter(status='completed').count()
    overdue_loans = loans.filter(status='overdue').count()
    
    # Financial statistics
    total_disbursed = loans.aggregate(total=Sum('principal_amount'))['total'] or 0
    total_collected = loans.aggregate(total=Sum('_amount_paid_cache'))['total'] or 0
    
    context = {
        'total_loans': total_loans,
        'active_loans': active_loans,
        'completed_loans': completed_loans,
        'overdue_loans': overdue_loans,
        'total_disbursed': total_disbursed,
        'total_collected': total_collected,
        'recent_loans': loans.order_by('-disbursement_date')[:20],
    }
    
    return render(request, 'reports/loan_reports.html', context)

@login_required
def collection_reports(request):
    """Collection reports with branch filtering"""
    user = request.user
    
    # Apply branch filtering
    branch_filter = {}
    if not user.is_superuser and hasattr(user, 'branch') and user.branch:
        branch_filter = {'loan__borrower__branch': user.branch}
    
    # Get repayment statistics
    repayments = Repayment.objects.filter(**branch_filter)
    
    # Basic statistics
    total_collections = repayments.aggregate(total=Sum('amount'))['total'] or 0
    collections_today = repayments.filter(
        payment_date=timezone.now().date()
    ).aggregate(total=Sum('amount'))['total'] or 0
    
    collections_this_month = repayments.filter(
        payment_date__month=timezone.now().month,
        payment_date__year=timezone.now().year
    ).aggregate(total=Sum('amount'))['total'] or 0
    
    context = {
        'total_collections': total_collections,
        'collections_today': collections_today,
        'collections_this_month': collections_this_month,
        'recent_payments': repayments.order_by('-payment_date')[:20],
    }
    
    return render(request, 'reports/collection_reports.html', context)

@login_required
def default_reports(request):
    """Default/overdue loan reports with branch filtering"""
    user = request.user
    
    # Apply branch filtering
    branch_filter = {}
    if not user.is_superuser and hasattr(user, 'branch') and user.branch:
        branch_filter = {'borrower__branch': user.branch}
    
    # Get overdue loans
    overdue_loans = Loan.objects.filter(status='overdue', **branch_filter)
    
    # Statistics
    total_overdue = overdue_loans.count()
    overdue_amount = overdue_loans.aggregate(total=Sum('outstanding_balance'))['total'] or 0
    
    # Categorize by overdue period
    today = timezone.now().date()
    overdue_30_days = overdue_loans.filter(due_date__lt=today - timedelta(days=30)).count()
    overdue_60_days = overdue_loans.filter(due_date__lt=today - timedelta(days=60)).count()
    overdue_90_days = overdue_loans.filter(due_date__lt=today - timedelta(days=90)).count()
    
    context = {
        'total_overdue': total_overdue,
        'overdue_amount': overdue_amount,
        'overdue_30_days': overdue_30_days,
        'overdue_60_days': overdue_60_days,
        'overdue_90_days': overdue_90_days,
        'overdue_loans': overdue_loans.order_by('-due_date')[:20],
    }
    
    return render(request, 'reports/default_reports.html', context)

@login_required
def rollover_reports(request):
    """Rollover reports with branch filtering"""
    user = request.user
    
    # Apply branch filtering
    branch_filter = {}
    if not user.is_superuser and hasattr(user, 'branch') and user.branch:
        branch_filter = {'borrower__branch': user.branch}
    
    # Get rollover statistics (assuming rollover is tracked in loan status or separate field)
    rolled_loans = Loan.objects.filter(status='rolled_over', **branch_filter)
    
    # Basic statistics
    total_rollovers = rolled_loans.count()
    rollover_amount = rolled_loans.aggregate(total=Sum('principal_amount'))['total'] or 0
    
    context = {
        'total_rollovers': total_rollovers,
        'rollover_amount': rollover_amount,
        'rolled_loans': rolled_loans.order_by('-created_at')[:20],
    }
    
    return render(request, 'reports/rollover_reports.html', context)

@login_required
def export_report(request, report_type):
    """Export reports in various formats"""
    user = request.user
    
    # Apply branch filtering
    branch_filter = {}
    if not user.is_superuser and hasattr(user, 'branch') and user.branch:
        branch_filter = {'borrower__branch': user.branch}
    
    if report_type == 'loans':
        loans = Loan.objects.filter(**branch_filter)
        
        # Create CSV response
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = f'attachment; filename="loans_report_{timezone.now().strftime("%Y%m%d")}.csv"'
        
        writer = csv.writer(response)
        writer.writerow(['Loan ID', 'Borrower', 'Amount', 'Status', 'Disbursement Date', 'Due Date'])
        
        for loan in loans:
            writer.writerow([
                loan.loan_id,
                loan.borrower.get_full_name(),
                loan.principal_amount,
                loan.status,
                loan.disbursement_date,
                loan.due_date
            ])
        
        return response
    
    elif report_type == 'borrowers':
        borrowers = CustomUser.objects.filter(role='borrower', **branch_filter)
        
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = f'attachment; filename="borrowers_report_{timezone.now().strftime("%Y%m%d")}.csv"'
        
        writer = csv.writer(response)
        writer.writerow(['Name', 'Email', 'Phone', 'Branch', 'Status', 'Date Joined'])
        
        for borrower in borrowers:
            writer.writerow([
                borrower.get_full_name(),
                borrower.email,
                borrower.phone_number,
                borrower.branch.name if borrower.branch else 'N/A',
                'Active' if borrower.is_active else 'Inactive',
                borrower.date_joined
            ])
        
        return response
    
    else:
        return HttpResponse("Invalid report type", status=400)

@login_required
def loan_analytics_dashboard(request):
    """Loan analytics dashboard with branch filtering"""
    user = request.user
    
    # Apply branch filtering
    branch_filter = {}
    if not user.is_superuser and hasattr(user, 'branch') and user.branch:
        branch_filter = {'borrower__branch': user.branch}
    
    # Get analytics data
    loans = Loan.objects.filter(**branch_filter)
    
    # Performance metrics
    total_loans = loans.count()
    approval_rate = 0
    if total_loans > 0:
        approved_loans = loans.filter(status__in=['active', 'completed']).count()
        approval_rate = (approved_loans / total_loans) * 100
    
    # Default rate
    overdue_loans = loans.filter(status='overdue').count()
    default_rate = (overdue_loans / total_loans * 100) if total_loans > 0 else 0
    
    # Average loan amount
    avg_loan_amount = loans.aggregate(avg=Avg('principal_amount'))['avg'] or 0
    
    context = {
        'total_loans': total_loans,
        'approval_rate': round(approval_rate, 2),
        'default_rate': round(default_rate, 2),
        'avg_loan_amount': avg_loan_amount,
        'loans': loans.order_by('-created_at')[:10],
    }
    
    return render(request, 'reports/loan_analytics_dashboard.html', context)

@login_required
def loan_analytics_report(request):
    """Detailed loan analytics report"""
    user = request.user
    
    # Apply branch filtering
    branch_filter = {}
    if not user.is_superuser and hasattr(user, 'branch') and user.branch:
        branch_filter = {'borrower__branch': user.branch}
    
    # Get detailed analytics
    loans = Loan.objects.filter(**branch_filter)
    
    # Monthly disbursement trend
    monthly_data = []
    for i in range(12):
        month_start = timezone.now().replace(day=1) - timedelta(days=30*i)
        month_end = (month_start + timedelta(days=32)).replace(day=1) - timedelta(days=1)
        
        monthly_loans = loans.filter(
            disbursement_date__range=[month_start, month_end]
        )
        
        monthly_data.append({
            'month': month_start.strftime('%b %Y'),
            'count': monthly_loans.count(),
            'amount': monthly_loans.aggregate(total=Sum('principal_amount'))['total'] or 0
        })
    
    # Status distribution
    status_data = []
    for status, label in Loan.STATUS_CHOICES:
        count = loans.filter(status=status).count()
        if count > 0:
            status_data.append({
                'status': label,
                'count': count,
                'percentage': (count / loans.count() * 100) if loans.count() > 0 else 0
            })
    
    context = {
        'monthly_data': list(reversed(monthly_data)),
        'status_data': status_data,
        'total_loans': loans.count(),
        'total_amount': loans.aggregate(total=Sum('principal_amount'))['total'] or 0,
    }
    
    return render(request, 'reports/loan_analytics_report.html', context)
'''
    
    # Read the current file
    file_path = "reports/views.py"
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Append the missing views to the end of the file
    content += missing_views_code
    
    # Write the updated content
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)
    
    print("✅ Added missing view functions to reports/views.py")

if __name__ == "__main__":
    add_missing_views()