import re

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

# Add serve_proxy_file after serve_file
serve_file_code = """@main_bp.route('/file/<int:file_id>')
@login_required
def serve_file(file_id):
    f = PrintFile.query.get_or_404(file_id)
    if f.user_id != current_user.id and not current_user.is_admin:
        abort(403)
    path = os.path.join(current_app.config['UPLOAD_FOLDER'], f.filename)
    return send_file(path)"""

proxy_code = """@main_bp.route('/file/<int:file_id>')
@login_required
def serve_file(file_id):
    f = PrintFile.query.get_or_404(file_id)
    if f.user_id != current_user.id and not current_user.is_admin:
        abort(403)
    path = os.path.join(current_app.config['UPLOAD_FOLDER'], f.filename)
    return send_file(path)

@main_bp.route('/proxy/<int:file_id>')
@login_required
def serve_proxy_file(file_id):
    f = PrintFile.query.get_or_404(file_id)
    if f.user_id != current_user.id and not current_user.is_admin:
        abort(403)
    path = os.path.join(current_app.config['UPLOAD_FOLDER'], f.filename)
    proxy_path = path + '.proxy.stl'
    if not os.path.exists(proxy_path):
        from stl_simplifier import simplify_stl
        try:
            simplify_stl(path, proxy_path, keep_ratio=0.1) # compress to 10%
        except:
            return send_file(path) # fallback to original if error
    if os.path.exists(proxy_path):
        return send_file(proxy_path)
    return send_file(path)"""

text = text.replace(serve_file_code, proxy_code)

# Change plater models to use serve_proxy_file
old_str = "url_for('main.serve_file', file_id=f.id)"
new_str = "url_for('main.serve_proxy_file', file_id=f.id)"

text = text.replace(old_str, new_str)

with open('app/routes.py', 'w', encoding='utf-8') as f:
    f.write(text)
print("Patched successfully")
