with open("public_html/supercerebro/js/app.js", "r") as f:
    lines = f.readlines()

target = 4967  # 0-indexed line 4968
check = lines[target]
if "fetch('api/save-config.php'" in check:
    # Insert CSRF token line before the fetch
    csrf_line = "  const csrf = document.querySelector('meta[name=\"dm-csrf\"]')?.content || '';\n"
    lines.insert(target, csrf_line)
    # Patch the fetch line (now at target+1)
    lines[target+1] = lines[target+1].replace(
        "headers:{'Content-Type':'application/json'}",
        "headers:{'Content-Type':'application/json','X-CSRF-Token':csrf}"
    )
    # Patch the catch line (now at target+3)
    for j in range(target+2, min(target+6, len(lines))):
        if "catch" in lines[j] and "save-config" in lines[j]:
            lines[j] = "    .catch(()=>{el.style.color='var(--red)';el.textContent='Error de red';});\n"
            break
    with open("public_html/supercerebro/js/app.js", "w") as f:
        f.writelines(lines)
    print("OK: CSRF added. New fetch line:", lines[target+1][:100])
else:
    print("ERROR line", target+1, ":", repr(check[:80]))
