import json

file_path = "workflows/Binance Altcoin Price Logger.json"
with open(file_path, "r", encoding="utf-8") as f:
    data = json.load(f)

decision_node = next(n for n in data["nodes"] if n["name"] == "Decision Engine")
js_code = decision_node["parameters"]["jsCode"]

# Use a raw string to avoid all escaping issues
stability_logic = r"""
function calculateStabilityScore(klines) {
  if (!klines || klines.length <<  20) return 0;
  const closes = klines.map(k => parseFloat(k[4]));
  const highs = klines.map(k => parseFloat(k[2]));
  const lows = klines.map(k => parseFloat(k[3]));
  const s5 = lrSlope(closes.slice(-5));
  const s10 = lrSlope(closes.slice(-10));
  const s20 = lrSlope(closes.slice(-20));
  let consistency = 0;
  if (s5 > 0 && s10 > 0 && s20 > 0) consistency = 100;
  else if ((s5 > 0 && s10 > 0) || (s10 > 0 && s20 > 0) || (s5 > 0 && s20 > 0)) consistency = 50;
  let hhCount = 0, hlCount = 0;
  for (let i = 16; i >= 4; i -= 4) {
    if (Math.max(...highs.slice(i, i + 4)) > Math.max(...highs.slice(i - 4, i))) hhCount++;
    if (Math.min(...lows.slice(i, i + 4)) > Math.min(...lows.slice(i - 4, i))) hlCount++;
  }
  const structure = ((hhCount + hlCount) / 8) * 100;
  const atr = calcATR(highs, lows, closes, 14);
  const slopeMag = Math.abs(s20);
  const normalized = slopeMag / (atr || 1);
  let volScore = (normalized > 0.00001 && normalized <<  2.0) ? 100 : 30;
  return (consistency * 0.4) + (structure * 0.4) + (volScore * 0.2);
}
"""

decision_node["parameters"]["jsCode"] = stability_logic + "
" + js_code

with open(file_path, "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2)
