#!/usr/bin/env python
"""
Test the clean dashboard with no button dependencies
"""
import os
import sys
import django

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

from django.test import Client

def test_clean_dashboard():
    """Test the completely clean dashboard"""
    print("🧹 Testing Clean Dashboard")
    print("=" * 50)
    
    client = Client()
    
    # Test 1: Dashboard loads
    print("\n1. Testing clean dashboard load...")
    try:
        response = client.get('/reports/')
        print(f"   ✅ Status: {response.status_code}")
        
        if response.status_code == 200:
            content = response.content.decode()
            
            # Check for clean template
            if 'clean_reports_dashboard.html' in str(response.template_name) or 'Clean Dashboard Loading' in content:
                print("   ✅ Clean template loaded")
            
            # Check for CSS
            if 'bootstrap' in content.lower() and 'chart.js' in content.lower():
                print("   ✅ CSS and Chart.js loaded")
            
            # Check for NO button dependencies
            if '6M' not in content and '1Y' not in content and 'btn6m' not in content:
                print("   ✅ NO 6M/1Y/ALL buttons found - CLEAN!")
            else:
                print("   ❌ Still has button dependencies")
            
            # Check for auto-loading
            if 'Auto-loading' in content or 'automatically' in content:
                print("   ✅ Auto-loading indicators present")
                
        elif response.status_code == 302:
            print("   ⚠️  Redirected (likely to login)")
        
    except Exception as e:
        print(f"   ❌ Error: {e}")
    
    # Test 2: Chart APIs work
    print("\n2. Testing chart APIs...")
    chart_types = ['loan_performance', 'portfolio_distribution', 'revenue_breakdown']
    
    for chart_type in chart_types:
        try:
            response = client.get(f'/reports/api/simple-chart-data/?chart_type={chart_type}')
            print(f"   📊 {chart_type}: Status {response.status_code}")
            
            if response.status_code == 200:
                data = response.json()
                if data.get('success'):
                    chart_data = data.get('data', {})
                    debug_info = data.get('debug', {})
                    
                    labels = len(chart_data.get('labels', []))
                    datasets = len(chart_data.get('datasets', []))
                    
                    print(f"      ✅ {labels} labels, {datasets} datasets")
                    
                    if debug_info.get('using_fallback'):
                        print(f"      ⚠️  Using fallback data")
                    else:
                        print(f"      ✅ Real data loaded")
                
        except Exception as e:
            print(f"   ❌ {chart_type}: {e}")
    
    # Test 3: Template files
    print("\n3. Checking template files...")
    templates = [
        'templates/reports/clean_reports_dashboard.html',
        'reports/simple_chart_api.py'
    ]
    
    for template in templates:
        if os.path.exists(template):
            print(f"   ✅ {template}")
        else:
            print(f"   ❌ Missing: {template}")
    
    print("\n" + "=" * 50)
    print("🎉 CLEAN DASHBOARD TEST COMPLETE!")
    
    print("\n✅ WHAT'S FIXED:")
    print("   • Completely new clean template")
    print("   • NO 6M, 1Y, ALL button dependencies")
    print("   • Charts auto-load on page load")
    print("   • Full CSS styling included")
    print("   • Fallback data prevents errors")
    print("   • Professional, modern design")
    
    print("\n🚀 HOW IT WORKS:")
    print("   1. Visit /reports/")
    print("   2. Clean template loads with full CSS")
    print("   3. Charts start loading automatically")
    print("   4. NO button clicks required")
    print("   5. Always shows data (real or fallback)")
    
    print("\n🎯 EXPECTED RESULT:")
    print("   ✅ Beautiful dashboard with full CSS")
    print("   ✅ Charts load automatically")
    print("   ✅ No 'Chart Unavailable' errors")
    print("   ✅ No button clicking required")
    
    print("\n🔗 Test it now: /reports/")

if __name__ == '__main__':
    test_clean_dashboard()