#!/usr/bin/env python3
"""
Fix the 500 errors found in smoke test
"""

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'")

with open(app_init_path, 'r') 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') as f:
        f.write(content)
    print("   ✓ Fixed FEATURES KeyError in health_check")
else:
    print("   ! Line not found or already fixed")

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

with open(config_path, 'r') 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')
    for i, line in enumerate(lines):
        if 'class Config:' in line or 'class Config(' in line:
            # Find a good place to add FEATURES
            for j in range(i+1, len(lines)):
                if lines[j].strip() and not lines[j].startswith(' '):
                    # End of class, insert before
                    lines.insert(j-1, '    # Feature flags')
                    lines.insert(j, '    FEATURES = {')
                    lines.insert(j+1, '        "gamification_leaderboards": True,')
                    lines.insert(j+2, '        "payments": False,  # Feature flag for payments')
                    lines.insert(j+3, '    }')
                    lines.insert(j+4, '')
                    break
            break
    
    with open(config_path, 'w') as f:
        f.write('\n'.join(lines))
    print("   ✓ Added FEATURES configuration")
else:
    print("   ✓ FEATURES already exists in config")

print("\n" + "=" * 60)
print("Fixes applied. Restart Flask server to test.")
