"""
Debug startup script - writes detailed logs to file
Upload this and temporarily set it as the startup file to diagnose issues
"""
import sys
import os
from datetime import datetime

# Create log file
log_file = '/home/bmdwtjuw/product-finder/startup_debug.log'

def log(message):
    with open(log_file, 'a') as f:
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        f.write(f"[{timestamp}] {message}\n")

try:
    log("="*70)
    log("STARTUP DEBUG - BEGIN")
    log("="*70)
    
    # Python info
    log(f"Python version: {sys.version}")
    log(f"Python executable: {sys.executable}")
    log(f"Current directory: {os.getcwd()}")
    
    # Environment variables
    log("\nEnvironment Variables:")
    log(f"  APPLICATION_ROOT: {os.environ.get('APPLICATION_ROOT', 'NOT SET')}")
    log(f"  FLASK_ENV: {os.environ.get('FLASK_ENV', 'NOT SET')}")
    
    # Python path
    log(f"\nPython path: {sys.path}")
    
    # Check Flask installation
    log("\nChecking Flask installation...")
    try:
        import flask
        log(f"  ✓ Flask version: {flask.__version__ if hasattr(flask, '__version__') else 'unknown'}")
    except ImportError as e:
        log(f"  ✗ Flask NOT installed: {e}")
        log("  RUN: pip install Flask==3.0.0 Werkzeug==3.0.1")
    
    # Check Werkzeug
    try:
        import werkzeug
        log(f"  ✓ Werkzeug version: {werkzeug.__version__ if hasattr(werkzeug, '__version__') else 'unknown'}")
    except ImportError as e:
        log(f"  ✗ Werkzeug NOT installed: {e}")
    
    # Check if app.py exists
    log("\nChecking files...")
    app_py_path = os.path.join(os.path.dirname(__file__), 'app.py')
    if os.path.exists(app_py_path):
        log(f"  ✓ app.py exists at {app_py_path}")
    else:
        log(f"  ✗ app.py NOT FOUND at {app_py_path}")
    
    # Try importing app
    log("\nAttempting to import Flask app...")
    try:
        from app import app
        log(f"  ✓ Successfully imported Flask app")
        log(f"  APPLICATION_ROOT config: {app.config.get('APPLICATION_ROOT', 'NOT SET')}")
        
        # Count routes
        routes = list(app.url_map.iter_rules())
        log(f"  ✓ Registered routes: {len(routes)}")
        
        # Create WSGI application
        def application(environ, start_response):
            log(f"\nRequest received: {environ.get('PATH_INFO', '/')}")
            return app(environ, start_response)
        
        log("\n✓ APPLICATION READY - Check site now")
        log("="*70)
        
    except Exception as e:
        log(f"  ✗ Failed to import app:")
        log(f"  Error: {e}")
        
        import traceback
        log(f"\nFull traceback:")
        log(traceback.format_exc())
        
        # Create error application
        def application(environ, start_response):
            status = '500 Internal Server Error'
            output = f'Import Error - Check {log_file}\n\n{traceback.format_exc()}'.encode('utf-8')
            response_headers = [('Content-type', 'text/plain'),
                                ('Content-Length', str(len(output)))]
            start_response(status, response_headers)
            return [output]
        
        log("="*70)

except Exception as e:
    # Catch-all for any errors
    import traceback
    log(f"\nFATAL ERROR during startup:")
    log(str(e))
    log(traceback.format_exc())
    log("="*70)
    
    def application(environ, start_response):
        status = '500 Internal Server Error'
        output = f'Startup Error - Check {log_file}'.encode('utf-8')
        response_headers = [('Content-type', 'text/plain'),
                            ('Content-Length', str(len(output)))]
        start_response(status, response_headers)
        return [output]
