#!/usr/bin/env python
"""
Comprehensive diagnosis script to find the exact server error
"""

import os
import sys
from pathlib import Path

print("=" * 70)
print("SERVER ERROR DIAGNOSIS")
print("=" * 70)
print()

# Setup environment
from dotenv import load_dotenv
BASE_DIR = Path(__file__).resolve().parent
load_dotenv(BASE_DIR / '.env', override=True)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')

# Test 1: Django imports
print("[1/8] Testing Django imports...")
try:
    import django
    django.setup()
    print("  ✓ Django setup successful")
except Exception as e:
    print(f"  ✗ Django setup failed: {e}")
    import traceback
    traceback.print_exc()
    sys.exit(1)
print()

# Test 2: Database connection
print("[2/8] Testing database connection...")
try:
    from django.db import connection
    with connection.cursor() as cursor:
        cursor.execute("SELECT 1")
        print("  ✓ Database connection works")
except Exception as e:
    print(f"  ✗ Database connection failed: {e}")
    import traceback
    traceback.print_exc()
print()

# Test 3: Import accounting models
print("[3/8] Testing accounting models import...")
try:
    from accounting.models import (
        Account, JournalEntry, JournalEntryLine, 
        GeneralLedger, FiscalPeriod, AccountBalance
    )
    print("  ✓ All accounting models imported")
except Exception as e:
    print(f"  ✗ Model import failed: {e}")
    import traceback
    traceback.print_exc()
print()

# Test 4: Query accounting data
print("[4/8] Testing accounting queries...")
try:
    from accounting.models import Account, FiscalPeriod
    account_count = Account.objects.count()
    period_count = FiscalPeriod.objects.count()
    print(f"  ✓ Accounts: {account_count}")
    print(f"  ✓ Fiscal Periods: {period_count}")
except Exception as e:
    print(f"  ✗ Query failed: {e}")
    import traceback
    traceback.print_exc()
print()

# Test 5: Import accounting views
print("[5/8] Testing accounting views import...")
try:
    import accounting.views
    print("  ✓ Views module imported")
    
    # Check if views are defined
    if hasattr(accounting.views, 'account_list'):
        print("  ✓ account_list view exists")
    else:
        print("  ✗ account_list view NOT FOUND")
        
except Exception as e:
    print(f"  ✗ Views import failed: {e}")
    import traceback
    traceback.print_exc()
print()

# Test 6: Import accounting URLs
print("[6/8] Testing accounting URLs...")
try:
    import accounting.urls
    print("  ✓ URLs module imported")
except Exception as e:
    print(f"  ✗ URLs import failed: {e}")
    import traceback
    traceback.print_exc()
print()

# Test 7: Check if accounting URLs are in main urls.py
print("[7/8] Checking main URL configuration...")
try:
    from django.urls import get_resolver
    resolver = get_resolver()
    
    # Check if accounting URLs are registered
    url_patterns = [str(p.pattern) for p in resolver.url_patterns]
    
    if any('accounting' in pattern for pattern in url_patterns):
        print("  ✓ Accounting URLs are registered")
    else:
        print("  ✗ Accounting URLs NOT registered in main urls.py")
        print("  Available patterns:", url_patterns)
except Exception as e:
    print(f"  ✗ URL check failed: {e}")
    import traceback
    traceback.print_exc()
print()

# Test 8: Test a simple accounting view directly
print("[8/8] Testing accounting view execution...")
try:
    from django.test import RequestFactory
    from django.contrib.auth.models import AnonymousUser
    from users.models import CustomUser
    
    # Try to import a view
    try:
        from accounting.views import account_list
        print("  ✓ account_list view imported")
        
        # Create a fake request
        factory = RequestFactory()
        request = factory.get('/accounting/accounts/')
        
        # Get a user
        user = CustomUser.objects.filter(role='admin').first()
        if user:
            request.user = user
            print(f"  ✓ Test user: {user.username}")
        else:
            request.user = AnonymousUser()
            print("  ! Using anonymous user")
        
        # Try to call the view
        try:
            response = account_list(request)
            print(f"  ✓ View executed, status: {response.status_code}")
        except Exception as e:
            print(f"  ✗ View execution failed: {e}")
            import traceback
            traceback.print_exc()
            
    except ImportError as e:
        print(f"  ✗ Views not defined yet: {e}")
        print("  This is expected if views.py is empty")
        
except Exception as e:
    print(f"  ✗ View test failed: {e}")
    import traceback
    traceback.print_exc()
print()

# Summary
print("=" * 70)
print("DIAGNOSIS COMPLETE")
print("=" * 70)
print()
print("If any test above shows ✗, that's where the error is.")
print()
print("Common issues:")
print("1. Missing views.py or empty views")
print("2. URLs not configured in main urls.py")
print("3. Missing templates")
print("4. Import errors in models or views")
print()
print("Check the errors above and fix the failing component.")
print()
