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

# Fix 1: Add CSRF token to saveCfg
old_fetch = "  fetch('api/save-config.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)})\n    .then(r=>r.json()).then(res=>{el.style.color=res.ok?'var(--g)':'var(--red)';el.textContent=res.ok?'\\u2713 Guardado':'\\u2717 '+(res.error||'Error');})\n    .catch(()=>{el.style.color='var(--y)';el.textContent='\\u26a0 Sube api/save-config.php';});"

new_fetch = "  const csrf = document.querySelector('meta[name=\"dm-csrf\"]')?.content || '';\n  fetch('api/save-config.php',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':csrf},body:JSON.stringify(data)})\n    .then(r=>r.json()).then(res=>{el.style.color=res.ok?'var(--g)':'var(--red)';el.textContent=res.ok?'\\u2713 Guardado':'\\u2717 '+(res.error||'Error');})\n    .catch(()=>{el.style.color='var(--red)';el.textContent='Error de red';});"

if old_fetch in content:
    content = content.replace(old_fetch, new_fetch, 1)
    with open("public_html/supercerebro/js/app.js", "w") as f:
        f.write(content)
    print("OK: CSRF token added to saveCfg")
else:
    # Try finding the fetch line differently
    idx = content.find("fetch('api/save-config.php'")
    if idx != -1:
        print("Found fetch at", idx)
        print(repr(content[idx-100:idx+200]))
    else:
        print("ERROR: saveCfg fetch not found")
