"""Parche idempotente: registra el blueprint de RA2 CDT1 en app.py y elimina
la ruta antigua @app.route("/ra2-cdt1") para que la sirva el blueprint.
Ejecutar dentro de ~/apps/quimica/ del servidor.
"""
import ast

APP = "app.py"

MARCA_IMPORT = "from reacciones_cdt import bp as reacciones_bp"
MARCA_REG = "app.register_blueprint(reacciones_bp)"
RUTA_VIEJA = '''@app.route("/ra2-cdt1")
def ra2_cdt1():
    return render_template("ra2-cdt1-iones.html")
'''


def main():
    with open(APP, encoding="utf-8") as f:
        texto = f.read()

    if "ra2_bp" in texto:
        print("app.py: ya registrado, omitiendo")
        return

    # 1. Añadir import del blueprint tras el de reacciones.
    if MARCA_IMPORT in texto:
        texto = texto.replace(
            MARCA_IMPORT,
            MARCA_IMPORT + "\nfrom ra2_cdt1 import bp as ra2_bp", 1)
    else:
        texto = texto.replace(
            "from ra3_cdt1 import bp as ra3_bp",
            "from ra3_cdt1 import bp as ra3_bp\nfrom ra2_cdt1 import bp as ra2_bp", 1)

    # 2. Registrar el blueprint.
    if MARCA_REG in texto:
        texto = texto.replace(
            MARCA_REG, MARCA_REG + "\napp.register_blueprint(ra2_bp)", 1)
    else:
        texto = texto.replace(
            "app.register_blueprint(ra3_bp)",
            "app.register_blueprint(ra3_bp)\napp.register_blueprint(ra2_bp)", 1)

    # 3. Eliminar la ruta antigua (ahora la sirve el blueprint).
    if RUTA_VIEJA in texto:
        texto = texto.replace(RUTA_VIEJA, "", 1)
        print("app.py: ruta antigua /ra2-cdt1 eliminada")

    ast.parse(texto)  # validación de sintaxis antes de escribir
    with open(APP, "w", encoding="utf-8") as f:
        f.write(texto)
    print("app.py: blueprint ra2 registrado (sintaxis validada)")


if __name__ == "__main__":
    main()
