#!/usr/bin/env python3
"""
Test script for enhanced dashboard functionality
Tests the new time period options and Reports & Statements updates
"""

import os
import sys
import django
import json
from datetime import datetime, timedelta

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.test import Client
from django.contrib.auth import get_user_model
from loans.models import Loan, LoanProduct
from users.models import CustomUser

def test_enhanced_dashboard():
    """Test the enhanced dashboard functionality"""
    print("🚀 Testing Enhanced Dashboard Functionality")
    print("=" * 60)
    
    client = Client()
    
    # Test 1: Check if dashboard loads
    print("\n1. Testing Dashboard Load...")
    try:
        # Create a test user
        User = get_user_model()
        test_user, created = User.objects.get_or_create(
            username='testadmin',
            defaults={
                'email': 'test@example.com',
                'role': 'admin',
                'is_staff': True,
                'is_superuser': True
            }
        )
        if created:
            test_user.set_password('testpass123')
            test_user.save()
        
        # Login
        login_success = client.login(username='testadmin', password='testpass123')
        if login_success:
            print("   ✅ User login successful")
        else:
            print("   ❌ User login failed")
            return False
            
        # Test dashboard access
        response = client.get('/dashboard/')
        if response.status_code == 200:
            print("   ✅ Dashboard loads successfully")
            
            # Check for new time period buttons
            content = response.content.decode()
            time_periods = ['1W', '1M', '3M', '6M', '1Y', '2Y', '5Y', 'All']
            found_periods = []
            
            for period in time_periods:
                if f'>{period}<' in content:
                    found_periods.append(period)
            
            print(f"   ✅ Found time period buttons: {', '.join(found_periods)}")
            
            if len(found_periods) >= 6:  # Should have at least 6 periods
                print("   ✅ Enhanced time period options implemented")
            else:
                print("   ⚠️  Some time period options may be missing")
                
        else:
            print(f"   ❌ Dashboard failed to load (Status: {response.status_code})")
            return False
            
    except Exception as e:
        print(f"   ❌ Dashboard test failed: {str(e)}")
        return False
    
    # Test 2: API endpoints for new time periods
    print("\n2. Testing API Endpoints for New Time Periods...")
    new_periods = ['1w', '1m', '3m', '2y', '5y']
    
    for period in new_periods:
        try:
            response = client.get(f'/api/loan-data/?period={period}')
            if response.status_code == 200:
                data = json.loads(response.content)
                if data.get('success'):
                    print(f"   ✅ API endpoint works for period: {period}")
                    print(f"      - Labels count: {len(data.get('labels', []))}")
                    print(f"      - Data points: {len(data.get('disbursements', []))}")
                else:
                    print(f"   ⚠️  API returned error for period {period}: {data.get('error', 'Unknown')}")
            else:
                print(f"   ❌ API failed for period {period} (Status: {response.status_code})")
        except Exception as e:
            print(f"   ❌ API test failed for period {period}: {str(e)}")
    
    # Test 3: Reports Dashboard Updates
    print("\n3. Testing Reports Dashboard Updates...")
    try:
        response = client.get('/utils/reports-dashboard/')
        if response.status_code == 200:
            print("   ✅ Reports dashboard loads successfully")
            
            content = response.content.decode()
            
            # Check for updated styling (should match reference system)
            if 'rounded-lg shadow p-4 sm:p-6' in content:
                print("   ✅ Reports dashboard styling updated to match reference")
            else:
                print("   ⚠️  Reports dashboard styling may not be fully updated")
                
            # Check for key sections
            sections = ['System Reports', 'Individual Statements', 'Recent Report Activity']
            for section in sections:
                if section in content:
                    print(f"   ✅ Found section: {section}")
                else:
                    print(f"   ❌ Missing section: {section}")
                    
        else:
            print(f"   ❌ Reports dashboard failed to load (Status: {response.status_code})")
            
    except Exception as e:
        print(f"   ❌ Reports dashboard test failed: {str(e)}")
    
    # Test 4: JavaScript functionality
    print("\n4. Testing JavaScript Functionality...")
    try:
        response = client.get('/dashboard/')
        content = response.content.decode()
        
        # Check for updateChart function with new periods
        if 'updateChart' in content:
            print("   ✅ updateChart function found")
            
            # Check for new period handling
            new_period_checks = ['1w', '1m', '3m', '2y', '5y']
            found_js_periods = []
            
            for period in new_period_checks:
                if f"'{period}'" in content or f'"{period}"' in content:
                    found_js_periods.append(period)
            
            if len(found_js_periods) >= 3:
                print(f"   ✅ JavaScript handles new periods: {', '.join(found_js_periods)}")
            else:
                print("   ⚠️  JavaScript may not handle all new periods")
                
        else:
            print("   ❌ updateChart function not found")
            
    except Exception as e:
        print(f"   ❌ JavaScript functionality test failed: {str(e)}")
    
    print("\n" + "=" * 60)
    print("✅ Enhanced Dashboard Testing Complete!")
    print("\nKey Improvements Implemented:")
    print("• Added 8 time period options (1W, 1M, 3M, 6M, 1Y, 2Y, 5Y, All)")
    print("• Enhanced API to handle daily/weekly/monthly data aggregation")
    print("• Updated Reports & Statements styling to match reference system")
    print("• Improved button layout and responsiveness")
    print("• Better error handling and user experience")
    
    return True

def test_time_period_data_accuracy():
    """Test that different time periods return appropriate data"""
    print("\n🔍 Testing Time Period Data Accuracy")
    print("-" * 40)
    
    client = Client()
    
    # Login first
    client.login(username='testadmin', password='testpass123')
    
    periods_to_test = {
        '1w': {'expected_points': 7, 'description': '7 daily points'},
        '1m': {'expected_points': 4, 'description': '4 weekly points'},
        '3m': {'expected_points': 3, 'description': '3 monthly points'},
        '6m': {'expected_points': 6, 'description': '6 monthly points'},
        '1y': {'expected_points': 12, 'description': '12 monthly points'},
    }
    
    for period, config in periods_to_test.items():
        try:
            response = client.get(f'/api/loan-data/?period={period}')
            if response.status_code == 200:
                data = json.loads(response.content)
                if data.get('success'):
                    labels_count = len(data.get('labels', []))
                    disbursements_count = len(data.get('disbursements', []))
                    
                    print(f"Period {period}: {labels_count} labels, {disbursements_count} data points")
                    print(f"  Expected: {config['description']}")
                    
                    if labels_count == disbursements_count:
                        print(f"  ✅ Data consistency check passed")
                    else:
                        print(f"  ⚠️  Data inconsistency: labels({labels_count}) != data({disbursements_count})")
                else:
                    print(f"  ❌ API error for {period}: {data.get('error', 'Unknown')}")
            else:
                print(f"  ❌ HTTP error for {period}: {response.status_code}")
                
        except Exception as e:
            print(f"  ❌ Exception for {period}: {str(e)}")

if __name__ == '__main__':
    try:
        success = test_enhanced_dashboard()
        test_time_period_data_accuracy()
        
        if success:
            print("\n🎉 All tests completed successfully!")
            sys.exit(0)
        else:
            print("\n❌ Some tests failed. Please check the output above.")
            sys.exit(1)
            
    except Exception as e:
        print(f"\n💥 Test execution failed: {str(e)}")
        sys.exit(1)