"""
Deployment diagnostic script for /product-finder
Run this on the server to verify configuration
"""
import os
import sys

print("=" * 70)
print("CGW PRODUCT FINDER - DEPLOYMENT DIAGNOSTIC")
print("=" * 70)
print()

# Check Python version
print("📌 Python Environment:")
print(f"   Version: {sys.version}")
print(f"   Executable: {sys.executable}")
print(f"   Current Directory: {os.getcwd()}")
print()

# Check environment variable
print("📌 Environment Variables:")
app_root_env = os.environ.get('APPLICATION_ROOT')
if app_root_env:
    print(f"   APPLICATION_ROOT: {app_root_env} ✓")
else:
    print(f"   APPLICATION_ROOT: NOT SET ⚠️")
    print(f"   Setting temporarily for test: /product-finder")
    os.environ['APPLICATION_ROOT'] = '/product-finder'
print()

# Try importing Flask
print("📌 Flask Installation:")
try:
    import flask
    print(f"   Flask version: {flask.__version__} ✓")
except ImportError as e:
    print(f"   ✗ Flask not installed: {e}")
    sys.exit(1)

# Try importing app
print()
print("📌 Application Import:")
try:
    from app import app
    print(f"   ✓ App imported successfully")
except Exception as e:
    print(f"   ✗ Error importing app:")
    print(f"   {e}")
    import traceback
    traceback.print_exc()
    sys.exit(1)

# Check app configuration
print()
print("📌 Application Configuration:")
print(f"   APPLICATION_ROOT: {app.config.get('APPLICATION_ROOT')}")
print(f"   SECRET_KEY set: {'Yes' if app.config.get('SECRET_KEY') else 'No'}")
print(f"   DEBUG mode: {app.config.get('DEBUG')}")
print(f"   ENV: {app.config.get('ENV', 'not set')}")
print()

# Check middleware
print("📌 WSGI Middleware:")
wsgi_app_type = type(app.wsgi_app).__name__
if 'PrefixMiddleware' in str(type(app.wsgi_app)):
    print(f"   ✓ PrefixMiddleware applied")
    print(f"   Type: {wsgi_app_type}")
elif wsgi_app_type == 'Flask':
    print(f"   ⚠️  No middleware applied (running at root)")
    print(f"   Type: {wsgi_app_type}")
else:
    print(f"   Middleware type: {wsgi_app_type}")
print()

# Check routes
print("📌 Registered Routes:")
routes_count = len(list(app.url_map.iter_rules()))
print(f"   Total routes: {routes_count}")

# Check critical routes
critical_routes = ['/login', '/api/login', '/users', '/api/session']
print(f"   Critical routes:")
for route in critical_routes:
    found = any(str(rule) == route for rule in app.url_map.iter_rules())
    status = "✓" if found else "✗"
    print(f"      {status} {route}")
print()

# Check file structure
print("📌 File Structure:")
critical_files = [
    'app.py',
    'passenger_wsgi.py',
    'config.py',
    'templates/login.html',
    'templates/index2.html',
    'data/users.json'
]

for file_path in critical_files:
    exists = os.path.exists(file_path)
    status = "✓" if exists else "✗"
    print(f"   {status} {file_path}")
print()

# Check dependencies
print("📌 Python Dependencies:")
deps = [
    ('werkzeug', 'Werkzeug'),
    ('flask', 'Flask'),
]

try:
    from PIL import Image
    deps.append(('PIL', 'Pillow'))
except ImportError:
    pass

for module_name, display_name in deps:
    try:
        module = __import__(module_name)
        version = getattr(module, '__version__', 'unknown')
        print(f"   ✓ {display_name}: {version}")
    except ImportError:
        print(f"   ✗ {display_name}: NOT INSTALLED")
print()

# Summary
print("=" * 70)
print("DEPLOYMENT STATUS")
print("=" * 70)

issues = []

if not os.environ.get('APPLICATION_ROOT'):
    issues.append("APPLICATION_ROOT not set in environment")

if app.config.get('APPLICATION_ROOT') == '/':
    issues.append("APPLICATION_ROOT is '/' but should be '/product-finder' for production")

if not os.path.exists('templates/login.html'):
    issues.append("Template files missing")

if not os.path.exists('data/users.json'):
    issues.append("User data file missing")

if issues:
    print()
    print("⚠️  ISSUES FOUND:")
    for issue in issues:
        print(f"   - {issue}")
    print()
    print("📝 NEXT STEPS:")
    print("   1. Upload missing files to server")
    print("   2. Set APPLICATION_ROOT environment variable")
    print("   3. Restart Passenger: touch tmp/restart.txt")
    print("   4. Check error logs for details")
else:
    print()
    print("✓ All checks passed!")
    print()
    print("🚀 DEPLOYMENT READY")
    print()
    print("To restart Passenger:")
    print("   mkdir -p tmp && touch tmp/restart.txt")
    print()
    print("To test:")
    print("   https://columbiawindows.com/product-finder/")

print()
print("=" * 70)
