#!/usr/bin/env python3
"""
Comprehensive app test script
Run this through control panel to diagnose issues
Writes detailed logs to test_app.log
"""
import sys
import os
from datetime import datetime

# Setup logging
log_file = os.path.join(os.path.dirname(__file__), 'test_app.log')

def log(message, also_print=True):
    """Write to log file and optionally print"""
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    full_message = f"[{timestamp}] {message}"
    
    with open(log_file, 'a') as f:
        f.write(full_message + '\n')
    
    if also_print:
        print(full_message)

try:
    log("="*70)
    log("APP TEST SCRIPT - START")
    log("="*70)
    
    # 1. Environment Info
    log("\n1. PYTHON ENVIRONMENT")
    log(f"   Python: {sys.version}")
    log(f"   Executable: {sys.executable}")
    log(f"   CWD: {os.getcwd()}")
    
    # 2. Check environment variables
    log("\n2. ENVIRONMENT VARIABLES")
    log(f"   APPLICATION_ROOT: {os.environ.get('APPLICATION_ROOT', 'NOT SET')}")
    log(f"   FLASK_ENV: {os.environ.get('FLASK_ENV', 'NOT SET')}")
    log(f"   SECRET_KEY: {'SET' if os.environ.get('SECRET_KEY') else 'NOT SET'}")
    
    # 3. Check critical files
    log("\n3. FILE STRUCTURE CHECK")
    files_to_check = [
        'app.py',
        'passenger_wsgi.py',
        'config.py',
        'data/users.json',
        'templates/login.html',
        'templates/index2.html',
        'templates/select_location.html',
        'templates/user_manager.html'
    ]
    
    all_files_exist = True
    for file_path in files_to_check:
        full_path = os.path.join(os.path.dirname(__file__), file_path)
        exists = os.path.exists(full_path)
        status = "✓" if exists else "✗ MISSING"
        log(f"   {status} {file_path}")
        if not exists:
            all_files_exist = False
    
    if not all_files_exist:
        log("\n⚠️  CRITICAL: Missing files detected!")
    
    # 4. Check dependencies
    log("\n4. PYTHON PACKAGES")
    packages = [
        ('flask', 'Flask'),
        ('werkzeug', 'Werkzeug')
    ]
    
    all_packages_ok = True
    for module_name, display_name in packages:
        try:
            module = __import__(module_name)
            try:
                from importlib.metadata import version
                ver = version(module_name)
            except:
                ver = getattr(module, '__version__', 'unknown')
            log(f"   ✓ {display_name}: {ver}")
        except ImportError as e:
            log(f"   ✗ {display_name}: NOT INSTALLED ({e})")
            all_packages_ok = False
    
    if not all_packages_ok:
        log("\n⚠️  CRITICAL: Missing packages! Run: pip install Flask==3.0.0 Werkzeug==3.0.1")
        sys.exit(1)
    
    # 5. Try importing app
    log("\n5. APP IMPORT TEST")
    log("   Attempting to import Flask app...")
    
    try:
        # Make sure current directory is in path
        current_dir = os.path.dirname(__file__)
        if current_dir not in sys.path:
            sys.path.insert(0, current_dir)
        
        from app import app
        log("   ✓ Flask app imported successfully!")
        
        # Check app config
        log("\n6. APP CONFIGURATION")
        log(f"   APPLICATION_ROOT: {app.config.get('APPLICATION_ROOT', 'NOT SET')}")
        log(f"   DEBUG: {app.config.get('DEBUG')}")
        log(f"   SECRET_KEY: {'SET (' + str(len(app.config.get('SECRET_KEY', ''))) + ' chars)' if app.config.get('SECRET_KEY') else 'NOT SET'}")
        
        # Check if middleware applied
        log(f"   WSGI App Type: {type(app.wsgi_app).__name__}")
        if 'PrefixMiddleware' in str(type(app.wsgi_app)):
            log("   ✓ PrefixMiddleware is active")
        else:
            log("   ⚠️  PrefixMiddleware NOT active (may cause issues at /product-finder)")
        
        # Count routes
        log("\n7. ROUTES CHECK")
        routes = list(app.url_map.iter_rules())
        log(f"   Total routes: {len(routes)}")
        
        # Check critical routes
        critical_routes = ['/login', '/api/login', '/users', '/select-location']
        log("   Critical routes:")
        for route_path in critical_routes:
            found = any(str(rule) == route_path or str(rule).startswith(route_path + '<') for rule in routes)
            status = "✓" if found else "✗ MISSING"
            log(f"     {status} {route_path}")
        
        # 8. Test loading users
        log("\n8. USER DATA TEST")
        try:
            users_file = os.path.join(current_dir, 'data', 'users.json')
            if os.path.exists(users_file):
                import json
                with open(users_file, 'r') as f:
                    users = json.load(f)
                log(f"   ✓ Users file loaded: {len(users)} users")
                log(f"   Usernames: {', '.join([u.get('username', '?') for u in users])}")
            else:
                log(f"   ✗ Users file NOT FOUND at {users_file}")
        except Exception as e:
            log(f"   ✗ Error loading users: {e}")
        
        # 9. Test a simple request
        log("\n9. REQUEST TEST")
        log("   Testing if app can handle requests...")
        
        with app.test_client() as client:
            # Test root redirect
            try:
                response = client.get('/')
                log(f"   GET / -> Status: {response.status_code}")
                if response.status_code == 302:
                    log(f"   Redirects to: {response.location}")
            except Exception as e:
                log(f"   ✗ Error testing /: {e}")
            
            # Test login page
            try:
                response = client.get('/login')
                log(f"   GET /login -> Status: {response.status_code}")
                if response.status_code != 200:
                    log(f"   ⚠️  Login page returned {response.status_code} instead of 200")
            except Exception as e:
                log(f"   ✗ Error testing /login: {e}")
        
        # 10. Summary
        log("\n" + "="*70)
        log("TEST SUMMARY")
        log("="*70)
        
        if all_files_exist and all_packages_ok:
            log("✓ All files present")
            log("✓ All packages installed")
            log("✓ App imports successfully")
            log(f"✓ {len(routes)} routes registered")
            
            app_root = app.config.get('APPLICATION_ROOT', '/')
            if app_root == '/product-finder':
                log("✓ Configured for /product-finder deployment")
            else:
                log(f"⚠️  APPLICATION_ROOT is '{app_root}' (should be '/product-finder' for production)")
            
            log("\n🎉 APP APPEARS READY!")
            log("\nIf still getting 500 errors:")
            log("1. Check that data/users.json exists")
            log("2. Verify APPLICATION_ROOT env var is set to /product-finder")
            log("3. Check Apache error log for runtime errors")
            log("4. Ensure .htaccess is correct")
            
        else:
            log("\n⚠️  ISSUES FOUND - Fix these before deployment")
        
        log("="*70)
        log(f"\nLog saved to: {log_file}")
        
    except ImportError as e:
        log(f"   ✗ FAILED to import app!")
        log(f"   Error: {e}")
        
        import traceback
        log("\nFull traceback:")
        log(traceback.format_exc())
        
        log("\n❌ CRITICAL ERROR: Cannot import Flask app")
        log("Check that app.py exists and has no syntax errors")
        
    except Exception as e:
        log(f"   ✗ Unexpected error during import!")
        log(f"   Error: {e}")
        
        import traceback
        log("\nFull traceback:")
        log(traceback.format_exc())

except Exception as e:
    log(f"\n❌ FATAL ERROR: {e}")
    import traceback
    log(traceback.format_exc())

finally:
    log("\n" + "="*70)
    log("TEST COMPLETE")
    log("="*70)
    print(f"\n📄 Full log saved to: {log_file}")
    print("Download this file to see all test results")
