#!/usr/bin/env zsh
set -euo pipefail

campaign="${1:-}"

if [[ -z "$campaign" ]]; then
  echo "usage: scripts/sync-preflight-config.v0.1.0.zsh <campaign>"
  exit 1
fi

# STREAM_PATH_NOTE: "awareness" is the hardcoded default stream name.
preflight_json="campaigns/content/$campaign/awareness/_sologen/json/preflight.json"
# STREAM_PATH_NOTE: "awareness" is the hardcoded default stream name.
config_json="campaigns/content/$campaign/awareness/_sologen/sologen.config.json"

if [[ ! -s "$preflight_json" ]]; then
  echo "[sync-preflight-config] skip: missing $preflight_json"
  exit 0
fi

tmp_out="$(mktemp)"

node -e '
const fs = require("fs");
const prePath = process.argv[1];
const cfgPath = process.argv[2];
const outPath = process.argv[3];

const isObj = (v) => v && typeof v === "object" && !Array.isArray(v);
const parseRatio01 = (v) => {
  if (v === null || v === undefined || v === "") return null;
  const n = Number(v);
  if (!Number.isFinite(n)) return null;
  if (n < 0) return 0;
  if (n > 1) return 1;
  return n;
};

let pre = {};
let cfg = {};
try { pre = JSON.parse(fs.readFileSync(prePath, "utf8")); } catch {}
try { cfg = JSON.parse(fs.readFileSync(cfgPath, "utf8")); } catch {}
if (!isObj(cfg)) cfg = {};

const validTemplate = new Set(["base", "essential", "pse"]);
const validTopChrome = new Set(["inline", "sticky"]);
const validIsiMode = new Set(["standard", "desktop_variant", "expanded_collapsed_variant", "none"]);

const next = { ...cfg };
let changed = false;
const updates = [];

const templateVariant = String(pre?.templateVariant || "").trim().toLowerCase();
if (validTemplate.has(templateVariant) && next.templateVariant !== templateVariant) {
  next.templateVariant = templateVariant;
  changed = true;
  updates.push(`templateVariant=${templateVariant}`);
}

const topChromeMode = String(pre?.topChromeMode || "").trim().toLowerCase();
if (validTopChrome.has(topChromeMode) && next.topChromeMode !== topChromeMode) {
  next.topChromeMode = topChromeMode;
  changed = true;
  updates.push(`topChromeMode=${topChromeMode}`);
}

const preIsi = isObj(pre?.isi) ? pre.isi : null;
if (preIsi) {
  const nextIsi = isObj(next?.isi) ? { ...next.isi } : {};
  let isiChanged = false;

  const mode = String(preIsi?.mode || "").trim().toLowerCase();
  if (validIsiMode.has(mode) && nextIsi.mode !== mode) {
    nextIsi.mode = mode;
    isiChanged = true;
    updates.push(`isi.mode=${mode}`);
  }

  const mob = parseRatio01(preIsi?.startHeight?.mobile);
  const desk = parseRatio01(preIsi?.startHeight?.desktop);
  if (mob !== null || desk !== null) {
    const prevStart = isObj(nextIsi.startHeight) ? { ...nextIsi.startHeight } : {};
    let startChanged = false;
    if (mob !== null && prevStart.mobile !== mob) {
      prevStart.mobile = mob;
      startChanged = true;
      updates.push(`isi.startHeight.mobile=${mob}`);
    }
    if (desk !== null && prevStart.desktop !== desk) {
      prevStart.desktop = desk;
      startChanged = true;
      updates.push(`isi.startHeight.desktop=${desk}`);
    }
    if (startChanged) {
      nextIsi.startHeight = prevStart;
      isiChanged = true;
    }
  }

  if (isiChanged) {
    next.isi = nextIsi;
    changed = true;
  }
}

if (!changed) {
  fs.writeFileSync(outPath, JSON.stringify({ changed: false, updates: [] }));
  process.exit(0);
}

fs.writeFileSync(cfgPath, JSON.stringify(next, null, 2) + "\n");
fs.writeFileSync(outPath, JSON.stringify({ changed: true, updates }));
' "$preflight_json" "$config_json" "$tmp_out"

sync_result="$(cat "$tmp_out" 2>/dev/null || echo '{"changed":false,"updates":[]}')"
rm -f "$tmp_out"

changed="$(node -e 'try{const x=JSON.parse(process.argv[1]);process.stdout.write(String(!!x.changed));}catch{process.stdout.write("false");}' "$sync_result")"
if [[ "$changed" == "true" ]]; then
  updates="$(node -e 'try{const x=JSON.parse(process.argv[1]);const u=Array.isArray(x.updates)?x.updates:[];process.stdout.write(u.join(", "));}catch{}' "$sync_result")"
  echo "[sync-preflight-config] updated $config_json${updates:+ ($updates)}"
else
  echo "[sync-preflight-config] no changes"
fi
