#!/usr/bin/env python
import os
import sys
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.template import Template, Context
from django.template.loader import get_template
from decimal import Decimal

def test_template_rendering():
    print("=== Testing Template Rendering ===")
    
    # Test data similar to what the service returns
    test_data = {
        'dashboard_data': {
            'summary_metrics': {
                'total_active_loans': 21,
                'total_portfolio_value': Decimal('546859.80'),
                'total_outstanding': Decimal('910037.00'),
                'collection_rate': 3.86,
                'loans_due_today': 0,
                'overdue_loans': 12,
            }
        }
    }
    
    # Test the template filters directly
    template_str = """
    {% load humanize %}
    Active Loans: {{ dashboard_data.summary_metrics.total_active_loans|default:0|floatformat:0 }}
    Portfolio Value: KES {{ dashboard_data.summary_metrics.total_portfolio_value|default:0|floatformat:0|intcomma }}
    Outstanding: KES {{ dashboard_data.summary_metrics.total_outstanding|default:0|floatformat:0|intcomma }}
    Collection Rate: {{ dashboard_data.summary_metrics.collection_rate|default:0|floatformat:1 }}%
    """
    
    template = Template(template_str)
    context = Context(test_data)
    rendered = template.render(context)
    
    print("Rendered template:")
    print(rendered)
    
    # Test individual values
    print("\nTesting individual values:")
    print(f"Raw portfolio value: {test_data['dashboard_data']['summary_metrics']['total_portfolio_value']}")
    print(f"Type: {type(test_data['dashboard_data']['summary_metrics']['total_portfolio_value'])}")
    
    # Test the filters manually
    from django.template.defaultfilters import floatformat
    from django.contrib.humanize.templatetags.humanize import intcomma
    
    portfolio_value = test_data['dashboard_data']['summary_metrics']['total_portfolio_value']
    formatted_value = floatformat(portfolio_value, 0)
    final_value = intcomma(formatted_value)
    
    print(f"After floatformat: {formatted_value}")
    print(f"After intcomma: {final_value}")

if __name__ == '__main__':
    test_template_rendering()