#!/usr/bin/env python3
"""
Fix the 500 errors found in smoke test - with proper encoding handling
"""

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

print("Analyzing 500 errors and applying fixes...")
print("=" * 60)

# Fix 1: Update app/__init__.py to handle missing FEATURES config
app_init_path = "app/__init__.py"
print(f"\n1. Fixing {app_init_path} - KeyError: 'FEATURES'")

try:
    with open(app_init_path, 'r', encoding='utf-8') as f:
        content = f.read()

    # Fix the health_check function to handle missing FEATURES
    old_line = '"gamification_active": app.config["FEATURES"].get("gamification_leaderboards", False),'
    new_line = '"gamification_active": app.config.get("FEATURES", {}).get("gamification_leaderboards", False),'

    if old_line in content:
        content = content.replace(old_line, new_line)
        with open(app_init_path, 'w', encoding='utf-8') as f:
            f.write(content)
        print("   ✓ Fixed FEATURES KeyError in health_check")
    else:
        print("   ! Line not found or already fixed")
except Exception as e:
    print(f"   Error fixing app/__init__.py: {e}")

# Fix 2: Add FEATURES to config if missing
config_path = "app/config.py"
print(f"\n2. Checking {config_path} for FEATURES")

try:
    with open(config_path, 'r', encoding='utf-8') as f:
        config_content = f.read()

    if 'FEATURES = {' not in config_content:
        print("   Adding FEATURES configuration...")
        # Add FEATURES to the Config class
        lines = config_content.split('\n')
        inserted = False
        
        for i, line in enumerate(lines):
            if 'class Config:' in line or 'class Config(' in line:
                # Find a good place to add FEATURES (after SECRET_KEY or DEBUG)
                for j in range(i+1, min(i+50, len(lines))):
                    if 'SECRET_KEY' in lines[j] or 'DEBUG' in lines[j]:
                        # Insert after this line
                        insert_idx = j + 1
                        while insert_idx < len(lines) and lines[insert_idx].strip() == '':
                            insert_idx += 1
                        
                        lines.insert(insert_idx, '')
                        lines.insert(insert_idx + 1, '    # Feature flags')
                        lines.insert(insert_idx + 2, '    FEATURES = {')
                        lines.insert(insert_idx + 3, '        "gamification_leaderboards": True,')
                        lines.insert(insert_idx + 4, '        "payments": False,  # Feature flag for payments')
                        lines.insert(insert_idx + 5, '    }')
                        inserted = True
                        break
                if inserted:
                    break
        
        if inserted:
            with open(config_path, 'w', encoding='utf-8') as f:
                f.write('\n'.join(lines))
            print("   ✓ Added FEATURES configuration")
        else:
            print("   ! Could not find appropriate location to add FEATURES")
    else:
        print("   ✓ FEATURES already exists in config")
except Exception as e:
    print(f"   Error fixing config.py: {e}")

# Fix 3: Check for /workers route issues
print(f"\n3. Checking /workers and /api/workers routes")

# Check if the routes exist in app/routes.py
routes_path = "app/routes.py"
try:
    with open(routes_path, 'r', encoding='utf-8') as f:
        routes_content = f.read()
    
    has_workers = '@app.route("/workers")' in routes_content or '@bp.route("/workers")' in routes_content
    has_api_workers = '@app.route("/api/workers")' in routes_content or '@bp.route("/api/workers")' in routes_content
    
    if has_workers:
        print("   ✓ /workers route exists")
    else:
        print("   ! /workers route not found")
    
    if has_api_workers:
        print("   ✓ /api/workers route exists")
    else:
        print("   ! /api/workers route not found")
        
except Exception as e:
    print(f"   Error checking routes: {e}")

print("\n" + "=" * 60)
print("Fixes applied. Next steps:")
print("1. Commit the changes")
print("2. Deploy to Fly.io: flyctl deploy -a rateright-au")
print("3. Re-run smoke tests")
