#!/usr/bin/env python
"""
Test the minimal dashboard
"""
import os
import sys
import django

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

from django.test import Client
import json

def test_minimal_dashboard():
    """Test the minimal dashboard with proper error handling"""
    print("🔧 Testing Minimal Dashboard")
    print("=" * 40)
    
    client = Client()
    
    # Test 1: Dashboard loads with CSS
    print("\n1. Testing dashboard load...")
    try:
        response = client.get('/reports/')
        print(f"   ✅ Status: {response.status_code}")
        
        if response.status_code == 200:
            content = response.content.decode()
            
            # Check for CSS
            if 'bootstrap' in content.lower():
                print("   ✅ Bootstrap CSS loaded")
            if 'background-color: #f8f9fa' in content:
                print("   ✅ Custom CSS loaded")
            if 'chart.js' in content.lower():
                print("   ✅ Chart.js loaded")
                
        elif response.status_code == 302:
            print("   ⚠️  Redirected (likely to login)")
        
    except Exception as e:
        print(f"   ❌ Error: {e}")
    
    # Test 2: Chart API returns valid JSON
    print("\n2. Testing chart API JSON...")
    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:
                # Test JSON parsing
                try:
                    data = response.json()
                    print(f"      ✅ Valid JSON response")
                    
                    if data.get('success'):
                        chart_data = data.get('data', {})
                        labels = len(chart_data.get('labels', []))
                        datasets = len(chart_data.get('datasets', []))
                        print(f"      ✅ {labels} labels, {datasets} datasets")
                        
                        if data.get('fallback'):
                            print(f"      ⚠️  Using fallback data")
                        else:
                            print(f"      ✅ Real data loaded")
                    else:
                        print(f"      ❌ Success=False in response")
                        
                except json.JSONDecodeError as e:
                    print(f"      ❌ JSON Parse Error: {e}")
                    # Print first 200 chars of response for debugging
                    content = response.content.decode()[:200]
                    print(f"      Raw response: {content}")
                
        except Exception as e:
            print(f"   ❌ {chart_type}: {e}")
    
    # Test 3: Template files exist
    print("\n3. Checking files...")
    files = [
        'templates/reports/minimal_dashboard.html',
        'reports/simple_chart_api.py'
    ]
    
    for file in files:
        if os.path.exists(file):
            print(f"   ✅ {file}")
        else:
            print(f"   ❌ Missing: {file}")
    
    print("\n" + "=" * 40)
    print("🎉 MINIMAL DASHBOARD TEST COMPLETE!")
    
    print("\n✅ FIXES APPLIED:")
    print("   • Minimal, clean template with embedded CSS")
    print("   • Removed login requirement from chart API")
    print("   • Fixed JSON parsing issues")
    print("   • Added proper error handling")
    print("   • Charts auto-load with fallback data")
    
    print("\n🚀 EXPECTED RESULTS:")
    print("   ✅ Dashboard loads with full CSS styling")
    print("   ✅ Charts load automatically without errors")
    print("   ✅ No JSON parsing errors")
    print("   ✅ Professional, clean interface")
    
    print("\n🔗 Test it now: /reports/")
    print("   • Should see beautiful dashboard with CSS")
    print("   • Charts should load automatically")
    print("   • No button clicking required")

if __name__ == '__main__':
    test_minimal_dashboard()