#!/usr/bin/env bash
# Offline determinism test for split + normalize (scripts/ha/lib/split.py,
# normalize.py): running the pipeline twice against the same fixture must
# produce byte-identical output. No network access, no HA instance needed.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
HA_LIB_DIR="$SCRIPT_DIR/../lib"
FIXTURE="$SCRIPT_DIR/fixtures/automations.yaml"

run_once() {
  local out_root="$1"
  mkdir -p "$out_root"
  python3 "$HA_LIB_DIR/split.py" "$FIXTURE" "$out_root" > /dev/null
}

TMP1="$(mktemp -d)"
TMP2="$(mktemp -d)"
trap 'rm -rf "$TMP1" "$TMP2"' EXIT

run_once "$TMP1"
run_once "$TMP2"

fail=0

if ! diff -r "$TMP1/automations" "$TMP2/automations" > /dev/null; then
  echo "FAIL: split+normalize output differs between two runs of the same fixture" >&2
  diff -r "$TMP1/automations" "$TMP2/automations" >&2 || true
  fail=1
else
  echo "PASS: split+normalize is deterministic across two runs"
fi

expected_files=(morning_lights.yaml goodnight.yaml low_battery_alert.yaml)
for f in "${expected_files[@]}"; do
  if [[ ! -f "$TMP1/automations/$f" ]]; then
    echo "FAIL: expected split output '$f' not found" >&2
    fail=1
  fi
done
if [[ "$fail" -eq 0 ]]; then
  echo "PASS: expected per-id automation files present"
fi

# re-running split against a directory that already holds a stale file (from
# a since-removed automation id) must remove it — split output should always
# mirror the source exactly, never accumulate stale files.
STALE_DIR="$(mktemp -d)"
trap 'rm -rf "$STALE_DIR"' EXIT
mkdir -p "$STALE_DIR/automations"
touch "$STALE_DIR/automations/removed_automation.yaml"
python3 "$HA_LIB_DIR/split.py" "$FIXTURE" "$STALE_DIR" > /dev/null
if [[ -f "$STALE_DIR/automations/removed_automation.yaml" ]]; then
  echo "FAIL: stale split output was not cleaned up" >&2
  fail=1
else
  echo "PASS: stale split output is cleaned up on re-run"
fi

exit "$fail"
