# Script to fix the beach_design route placement in admin_routes.py

import os

# Read the original file
file_path = r'd:\bookbeach\backend\app\routes\admin_routes.py'
with open(file_path, 'r', encoding='utf-8') as f:
    content = f.read()

# Remove the misplaced route (if it exists in the wrong place)
# Look for the misplaced route pattern
lines = content.split('\n')
fixed_lines = []
i = 0
while i < len(lines):
    line = lines[i]
    # Check if we found the misplaced route
    if line.strip() == '@admin_bp.route(\'/beaches/<beach_id>/design\', methods=[\'GET\'])':
        # Skip this line and the following lines until we reach the except block
        print(f"Found misplaced route at line {i}")
        # Skip until we find the correct end of the misplaced route
        while i < len(lines) and not (lines[i].strip() == 'finally:' or 
                                     (i+1 < len(lines) and lines[i+1].strip().startswith('@admin_bp.route')) or
                                     (i+1 < len(lines) and lines[i+1].strip() == '' and i+2 < len(lines) and lines[i+2].strip().startswith('def '))):
            i += 1
        # Skip the finally block as well
        if i < len(lines) and lines[i].strip() == 'finally:':
            while i < len(lines) and lines[i].strip() != '':
                i += 1
        print(f"Skipped misplaced route, now at line {i}")
        continue
    fixed_lines.append(line)
    i += 1

# Add the route at the end of the file
beach_design_route = '''

@admin_bp.route('/beaches/<beach_id>/design', methods=['GET'])
@login_required
def beach_design(beach_id):
    """Full screen beach design page"""
    # Check if user is logged in and is admin
    if not session.get('is_admin'):
        flash('You must be logged in as an administrator to access this page.', 'error')
        return redirect(url_for('admin.admin_login'))
    
    try:
        # Redirect to the static Vue application with just the beach ID
        return redirect(f"/static/BeachDesign/index.html?beach_id={beach_id}")
        
    except Exception as e:
        error_msg = f'Error loading beach design: {str(e)}'
        print(f"BEACH DESIGN ERROR: {error_msg}")
        flash(error_msg, 'error')
        # Redirect back to beach edit page
        return redirect(url_for('admin.edit_beach', beach_id=beach_id))
'''

# Append the route to the end
fixed_content = '\n'.join(fixed_lines) + beach_design_route

# Write the fixed content back to the file
with open(file_path, 'w', encoding='utf-8') as f:
    f.write(fixed_content)

print("Fixed the beach_design route placement in admin_routes.py")