#!/usr/bin/env python
"""
Test application
Tests if the application can start and work without running migrations
"""

import os
import sys
import django
from django.core.management import execute_from_command_line

def setup_django():
    """Setup Django environment"""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
    django.setup()

def test_application():
    """Test if the application can start"""
    print("=== TESTING APPLICATION ===")
    
    try:
        # Try to import the main settings
        from django.conf import settings
        print("✓ Django settings loaded successfully")
        
        # Try to import main models
        from users.models import CustomUser
        print("✓ Users models imported successfully")
        
        from loans.models import Loan
        print("✓ Loans models imported successfully")
        
        from utils.models import AuditLog
        print("✓ Utils models imported successfully")
        
        # Try to import reports models (might fail)
        try:
            from reports.models import LoanScoring
            print("✓ Reports models imported successfully")
        except Exception as e:
            print(f"⚠ Reports models import failed: {e}")
        
        print("✓ Application components are working")
        return True
        
    except Exception as e:
        print(f"⚠ Application test failed: {e}")
        return False

def run_server():
    """Try to run the development server"""
    print("\n=== RUNNING DEVELOPMENT SERVER ===")
    
    try:
        print("Starting development server...")
        print("Press Ctrl+C to stop the server")
        execute_from_command_line(['manage.py', 'runserver', '0.0.0.0:8000'])
        return True
        
    except KeyboardInterrupt:
        print("\n✓ Server stopped by user")
        return True
    except Exception as e:
        print(f"⚠ Server failed to start: {e}")
        return False

def main():
    """Main function"""
    print("=== APPLICATION TEST ===")
    print("Testing if the application can start and work.\n")
    
    try:
        setup_django()
        
        # Test the application
        if test_application():
            print("\n=== APPLICATION TEST SUCCESSFUL ===")
            print("✓ Application components are working")
            print("✓ You can now start the server")
            print("\n📋 To start the server manually:")
            print("python manage.py runserver")
            print("\n📋 Or run this script to start the server automatically:")
            print("python test_application.py --run-server")
            
            # Check if user wants to run the server
            if '--run-server' in sys.argv:
                run_server()
            
            return True
        else:
            print("\n=== APPLICATION TEST FAILED ===")
            print("⚠ Application has issues")
            return False
        
    except Exception as e:
        print(f"\n❌ Test failed: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
