#!/usr/bin/env bash
# tests/office1-record-dump/run-tests.sh
#
# OFFLINE unit harness for netbox/office1-record-dump.py's PURE transform functions
# (slim / prefix-scope rewrite / ip-range key). NO network, no live NetBox -- the
# network path (get_all) is not exercised here; this proves the record->JSON shaping
# that a downstream fidelity/diff depends on. Mutates NOTHING.
# Exit: 0 all pass | 1 any failed.  ASCII + LF.
set -uo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO="$(cd "$HERE/../.." && pwd)"
MOD="$REPO/netbox/office1-record-dump.py"

python3 - "$MOD" <<'PY'
import sys, importlib.util
spec = importlib.util.spec_from_file_location("o1dump", sys.argv[1])
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)

P = F = 0
def ok(cond, label):
    global P, F
    if cond: print("  PASS  %s" % label); P += 1
    else:    print("  FAIL  %s" % label); F += 1

# T1 slim keeps only requested fields, resolves a nested ref to its slug
r = m.slim({"prefix": "10.12.64.0/22", "role": {"slug": "provider-public", "id": 9},
            "status": {"value": "active"}, "extra": "dropped"},
           ["prefix", "role", "status"])
ok(r == {"prefix": "10.12.64.0/22", "role": "provider-public", "status": "active"},
   "T1 slim resolves nested ref->slug/value and drops unrequested fields")

# T2 slim keeps a missing field as None (stable schema)
ok(m.slim({"prefix": "x"}, ["prefix", "role"]) == {"prefix": "x", "role": None},
   "T2 slim fills a missing field with None")

# T3 prefix scope rewrite: dcim.site id -> scope_site slug, scope_id dropped
rec = m.rewrite_prefix_scope({"prefix": "p", "scope_type": "dcim.site", "scope_id": 5},
                             {"scope_id": 5, "scope_type": "dcim.site"},
                             {5: "vr1-dc1"}, {})
ok(rec.get("scope_site") == "vr1-dc1" and "scope_id" not in rec,
   "T3 prefix scope dcim.site -> scope_site slug, scope_id dropped")

# T4 prefix scope rewrite: dcim.region id -> scope_region slug (the region-scoped case)
rec = m.rewrite_prefix_scope({"prefix": "p"},
                             {"scope_id": 2, "scope_type": "dcim.region"},
                             {}, {2: "vr1"})
ok(rec.get("scope_region") == "vr1" and "scope_id" not in rec,
   "T4 prefix scope dcim.region -> scope_region slug")

# T5 the record source is office1-netbox via the RECORD env (source separation);
#    require_env names the sandbox env, and the Usage line sources it -- prove it targets
#    the record, not the frozen reference.
import inspect
src = inspect.getsource(m)
ok("office1-netbox" in src and "vr1-netbox-sandbox.env" in src and "10.10.1.10:8000" in src,
   "T5 script targets the RECORD (office1-netbox 10.10.1.10:8000 / sandbox env)")

print("\nRESULT: PASS=%d FAIL=%d" % (P, F))
sys.exit(1 if F else 0)
PY
rc=$?
[[ "$rc" -eq 0 ]] && echo "ALL PASS" || echo "SOME FAILED"
exit $rc
