#!/usr/bin/env bash
# Read-only Drift-Audit: Live-Stand (/opt/data) vs. Git-Server-Stand (origin/main)
# Aendert NICHTS. Nutzung: bash scripts/config-drift.sh [repo] [src]
set -uo pipefail

REPO="${1:-/opt/data/Hermes-Config}"
SRC="${2:-/opt/data}"
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

cd "$REPO" || { echo "REPO nicht lesbar: $REPO"; exit 1; }
git fetch -q origin || { echo "FETCH FAILED (Auth/Netz?)"; exit 1; }

echo "== Server-Stand =="
echo "HEAD        : $(git rev-parse HEAD)"
echo "origin/main : $(git rev-parse origin/main)"
echo "ls-remote   : $(git ls-remote origin main | cut -f1)"
echo "Arbeitskopie: $(git status --porcelain | wc -l) geaenderte Dateien (nur die KOPIE - NICHT der Live-Stand!)"
echo

echo "== Drift je getrackter Datei (Live-Datei vs origin/main) =="
while IFS= read -r f; do
  [ "$f" = ".gitignore" ] && continue
  live="$SRC/$f"
  if [ ! -f "$live" ]; then
    echo "NO-LIVE    $f   (nur im Repo - vom Sync-Skript erzeugt oder absichtlich ausgeschlossen)"
    continue
  fi
  n=$(git show "origin/main:$f" | diff - "$live" | grep -c '^[<>]')
  [ "$n" -gt 0 ] && echo "DIFF($n)    $f"
done < <(git ls-tree -r --name-only origin/main)
echo

echo "== Live-only Dateien (im Snapshot-Scope, aber noch nicht im Server-Stand) =="
# Repo-Liste und Live-Liste des Snapshot-Scopes vergleichen.
git ls-tree -r --name-only origin/main | sort -u > "$TMP/repo.lst"
(
  cd "$SRC" || exit 0
  find skills memories scripts -type f 2>/dev/null
  echo config.yaml
  echo SOUL.md
  echo cron/jobs.json
  echo home/.config/himalaya/config.toml
  echo plugins/.install-metadata.json
) | sort -u > "$TMP/live.lst"
# Vom Sync-Skript ausgeschlossene Pfade sind kein Befund.
comm -13 "$TMP/repo.lst" "$TMP/live.lst" \
  | grep -vE '(^|/)(\.hub|\.locks|\.curator_state|\.curator_ledger\.jsonl|\.bundled_manifest|\.usage\.json)(/|$)' \
  | grep -vE '\.lock$' \
  | grep -v '^scripts/whatsapp-bridge/' \
  | sed 's/^/LIVE-ONLY /' || true
echo

echo "== config.yaml: geaenderte Zeilen (Secret-Zeilen maskiert) =="
git show "origin/main:config.yaml" | diff -u - "$SRC/config.yaml" \
  | grep -E '^[+-][^+-]' \
  | sed -E 's/^([+-][[:space:]]*[A-Za-z0-9_.-]*(key|token|secret|password|passwd)[A-Za-z0-9_.-]*:).*/\1 <WERT MASKIERT>/I'
echo

echo "== cron/jobs.json: Drift OHNE Laufzeit-Felder (leer = nur Runtime-Drift) =="
git show "origin/main:cron/jobs.json" | diff - "$SRC/cron/jobs.json" \
  | grep -E '^[<>]' \
  | grep -vE '"(completed|next_run_at|last_run_at|scheduled_at|dispatched_at|lateness_seconds|updated_at)"' \
  | head -20
echo

if command -v python3 >/dev/null 2>&1 && python3 -c 'import yaml' 2>/dev/null; then
  echo "== Typ-Drift in config.yaml (Str vs Int usw.) =="
  git show "origin/main:config.yaml" > "$TMP/old.yaml"
  cp "$SRC/config.yaml" "$TMP/new.yaml"
  python3 - "$TMP/old.yaml" "$TMP/new.yaml" <<'PY'
import sys, yaml
def flat(o, p=""):
    if isinstance(o, dict):
        for k, v in o.items():
            yield from flat(v, f"{p}.{k}" if p else str(k))
    elif isinstance(o, list):
        for i, v in enumerate(o):
            yield from flat(v, f"{p}[{i}]")
    else:
        yield p, o
a = dict(flat(yaml.safe_load(open(sys.argv[1])) or {}))
b = dict(flat(yaml.safe_load(open(sys.argv[2])) or {}))
found = False
for k in sorted(set(a) & set(b)):
    ta, tb = type(a[k]).__name__, type(b[k]).__name__
    if ta != tb:
        found = True
        print(f"TYP-DRIFT  {k}: {ta} -> {tb}")
for k in sorted(set(b) - set(a)):
    print(f"NEU        {k} = {type(b[k]).__name__}  (im Server-Stand nicht vorhanden)")
for k in sorted(set(a) - set(b)):
    print(f"WEG        {k}  (im Server-Stand vorhanden, live nicht)")
if not found:
    print("(keine Typ-Drift bei gemeinsamen Keys)")
PY
  echo
fi

echo "== Zeitliche Einordnung =="
echo "live config.yaml mtime : $(stat -c '%y' "$SRC/config.yaml")"
echo "letzter Commit (config): $(git log -1 --format='%h %ad %s' --date=iso -- config.yaml)"
