import re
with open('src/main.cpp', 'r') as f:
    content = f.read()

# Make logLine print to serial
content = content.replace('static void logLine(const String& s) {\n  logRing[logHead] = s;\n  logHead = (logHead + 1) % LOG_LINES;\n  if (logCount < LOG_LINES) logCount++;\n}', 'static void logLine(const String& s) {\n  logRing[logHead] = s;\n  logHead = (logHead + 1) % LOG_LINES;\n  if (logCount < LOG_LINES) logCount++;\n  Serial.println(s);\n}')

# Fix jammingEnabled check
content = content.replace('  if (jammingEnabled) {\n    logLine("[JAM] Already jamming, ignoring start request");\n    return;\n  }', '  if (jammingEnabled) {\n    logLine("[JAM] Already jamming, ignoring start request");\n    // return; // Allow re-initialization if needed\n  }')

# Move kHtml to global scope
html_pattern = r'(static const char kHtml\[\] PROGMEM = R"HTML\([\s\S]*?\)HTML";)'
match = re.search(html_pattern, content)
if match:
    html_block = match.group(1).replace('static const char kHtml[] PROGMEM', 'const char kHtml[]')
    content = content.replace(match.group(1), '')
    
    # insert before handleRoot
    content = content.replace('static void handleRoot() {', html_block + '\n\nstatic void handleRoot() {')

# Fix send_P to send
content = content.replace('server.send_P(200, "text/html; charset=utf-8", kHtml);', 'server.send(200, "text/html; charset=utf-8", kHtml);')

# Fix initial jam start
content = content.replace('  // Start jamming immediately if enabled\n  if (jammingEnabled) {\n    startJamming();\n  } else {', '  // Start jamming immediately if enabled\n  if (jammingEnabled) {\n    jammingEnabled = false;\n    startJamming();\n  } else {')

with open('src/main.cpp', 'w') as f:
    f.write(content)
