import re

def update_main_routes():
    with open('app/routes/main_routes.py', 'r', encoding='utf-8') as f:
        text = f.read()

    # Create the API endpoint
    api_endpoint = """
@main_bp.route('/api/engine_options/<engine_name>')
@login_required
def engine_options(engine_name):
    from app.utils.slice_engines import get_slicer_engine
    engine = get_slicer_engine(engine_name)
    presets = engine.get_quality_presets(current_app)
    patterns = engine.get_support_patterns()
    return jsonify({'presets': presets, 'support_patterns': patterns})
"""
    if "def engine_options(engine_name):" not in text:
        text += api_endpoint
        
    # Overwrite the old get_quality_presets
    old_func = re.search(r'def get_quality_presets\(\):.*?(?=@main_bp\.route|\Z)', text, re.DOTALL)
    if old_func:
        text = text.replace(old_func.group(0), "")
        
    # Replace in plater()
    if 'presets = get_quality_presets()' in text:
        text = text.replace("presets = get_quality_presets()", "")
    
    with open('app/routes/main_routes.py', 'w', encoding='utf-8') as f:
        f.write(text)

def update_admin_routes():
    with open('app/routes/admin_routes.py', 'r', encoding='utf-8') as f:
        text = f.read()
        
    text = re.sub(r'from app\.utils\.print_config import get_quality_presets\n', '', text)
    
    old_ret = """    configs = {c.key: c.value for c in SystemConfig.query.all()}
    presets = get_quality_presets()
    engines = get_all_engines()
    return render_template('admin/settings.html', configs=configs, presets=presets, engines=engines)"""
    
    new_ret = """    configs = {c.key: c.value for c in SystemConfig.query.all()}
    engines = get_all_engines()
    return render_template('admin/settings.html', configs=configs, engines=engines)"""
    
    if old_ret in text:
        text = text.replace(old_ret, new_ret)
        
    old_func = re.search(r'def get_quality_presets\(\):.*?(?=@admin_bp\.route|\Z)', text, re.DOTALL)
    if old_func:
        text = text.replace(old_func.group(0), "")
        
    with open('app/routes/admin_routes.py', 'w', encoding='utf-8') as f:
        f.write(text)

update_main_routes()
update_admin_routes()
print("Routes patched")
