#!/usr/bin/env bash
# Tests for check-brand-cache.sh (Task 2019). Fixture-driven: builds a throwaway
# install dir + config dir per case and stubs the fetch command, because the real
# one crosses a Cloudflare edge that no test can hold still. sha256 and the
# ingress parse are the real code paths — those are what this asserts.
set -uo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CHECK="$SCRIPT_DIR/../check-brand-cache.sh"

PASS=0
FAIL=0

run_case() {
  local name="$1"; shift
  echo ""
  echo "=== CASE: $name ==="
  if "$@"; then
    PASS=$((PASS + 1)); echo "PASS: $name"
  else
    FAIL=$((FAIL + 1)); echo "FAIL: $name"
  fi
}

# Build install dir with two brand files and brand-defaults.css. Echoes its path.
mk_install() {
  local d
  d="$(mktemp -d "${TMPDIR:-/tmp}/brand-cache-install.XXXXXX")"
  mkdir -p "$d/server/public/brand"
  printf 'lime-logo-bytes' > "$d/server/public/brand/logo.png"
  printf 'lime-icon-bytes' > "$d/server/public/brand/icon.png"
  printf ':root{--brand:#c3f53c}' > "$d/server/public/brand-defaults.css"
  echo "$d"
}

# Build a config dir whose cloudflared/config.yml has the given ingress hosts.
mk_config_with_hosts() {
  local d; d="$(mktemp -d "${TMPDIR:-/tmp}/brand-cache-config.XXXXXX")"
  mkdir -p "$d/cloudflared"
  { echo "ingress:"; for h in "$@"; do echo "  - hostname: $h"; done; echo "  - service: http_status:404"; } \
    > "$d/cloudflared/config.yml"
  echo "$d"
}

mk_config_no_tunnel() {
  local d; d="$(mktemp -d "${TMPDIR:-/tmp}/brand-cache-config.XXXXXX")"
  echo "$d"
}

# A config dir with no cloudflared ingress but an alias-domains.json, the
# second source resolvePublicHostname reads.
mk_config_alias_only() {
  local d; d="$(mktemp -d "${TMPDIR:-/tmp}/brand-cache-config.XXXXXX")"
  printf '["public.realagent.app"]' > "$d/alias-domains.json"
  echo "$d"
}

# Stub curl. $1 = dir whose files it serves as the "edge", keyed by basename.
# Writes headers to the -D path and the body to the -o path, exit 0.
mk_curl_stub() {
  local serve_dir="$1" stub
  stub="$(mktemp "${TMPDIR:-/tmp}/brand-cache-curl.XXXXXX")"
  cat > "$stub" <<STUB
#!/usr/bin/env bash
hdr=""; out=""; url=""
while [ \$# -gt 0 ]; do
  case "\$1" in
    -D) hdr="\$2"; shift 2 ;;
    -o) out="\$2"; shift 2 ;;
    -*) shift ;;
    *) url="\$1"; shift ;;
  esac
done
name="\${url##*/}"
printf 'HTTP/2 200\r\ncf-cache-status: HIT\r\nage: 5352\r\n\r\n' > "\$hdr"
cat "$serve_dir/\$name" > "\$out"
STUB
  chmod +x "$stub"
  echo "$stub"
}

case_clean_install_reports_clean() {
  local i c stub edge out rc
  i="$(mk_install)"; c="$(mk_config_with_hosts operations.realagent.network)"
  # Edge serves exactly what is on disk.
  edge="$(mktemp -d "${TMPDIR:-/tmp}/brand-cache-edge.XXXXXX")"
  cp "$i/server/public/brand/"* "$edge/"
  cp "$i/server/public/brand-defaults.css" "$edge/"
  stub="$(mk_curl_stub "$edge")"
  out="$(BRAND_CACHE_CURL="$stub" "$CHECK" --install-dir "$i" --config-dir "$c" 2>/dev/null)"
  rc=$?
  [ "$rc" -eq 0 ] || { echo "  expected exit 0, got $rc"; rm -rf "$i" "$c" "$edge" "$stub"; return 1; }
  # files=2 pinned as an integer: a \d+ match also accepts files=0, and a
  # hostname resolving to nothing would then read as a pass.
  echo "$out" | grep -qx "\[brand-cache\] clean host=operations.realagent.network files=2" \
    || { echo "  no clean line with files=2; got: $out"; rm -rf "$i" "$c" "$edge" "$stub"; return 1; }
  rm -rf "$i" "$c" "$edge" "$stub"; return 0
}

case_stale_edge_reports_stale_on_stderr() {
  local i c stub edge err rc
  i="$(mk_install)"; c="$(mk_config_with_hosts operations.realagent.network)"
  edge="$(mktemp -d "${TMPDIR:-/tmp}/brand-cache-edge.XXXXXX")"
  cp "$i/server/public/brand/"* "$edge/"
  cp "$i/server/public/brand-defaults.css" "$edge/"
  # The measured symptom: the edge holds the retired mark, disk holds the new one.
  printf 'black-square-bytes' > "$edge/logo.png"
  stub="$(mk_curl_stub "$edge")"
  err="$(BRAND_CACHE_CURL="$stub" "$CHECK" --install-dir "$i" --config-dir "$c" 2>&1 >/dev/null)"
  rc=$?
  [ "$rc" -eq 1 ] || { echo "  expected exit 1, got $rc"; rm -rf "$i" "$c" "$edge" "$stub"; return 1; }
  echo "$err" | grep -qE "^\[brand-cache\] STALE host=operations\.realagent\.network path=/brand/logo\.png edge=[0-9a-f]{7} disk=[0-9a-f]{7} cf-cache-status=HIT age=5352$" \
    || { echo "  no STALE line for /brand/logo.png; got: $err"; rm -rf "$i" "$c" "$edge" "$stub"; return 1; }
  rm -rf "$i" "$c" "$edge" "$stub"; return 0
}

case_no_tunnel_reports_skipped() {
  local i c out rc
  i="$(mk_install)"; c="$(mk_config_no_tunnel)"
  out="$("$CHECK" --install-dir "$i" --config-dir "$c" 2>/dev/null)"
  rc=$?
  [ "$rc" -eq 0 ] || { echo "  expected exit 0, got $rc"; rm -rf "$i" "$c"; return 1; }
  echo "$out" | grep -qx "\[brand-cache\] skipped host=none reason=no-tunnel-ingress" \
    || { echo "  no skipped line; got: $out"; rm -rf "$i" "$c"; return 1; }
  rm -rf "$i" "$c"; return 0
}

case_localhost_only_ingress_is_no_tunnel() {
  local i c out rc
  i="$(mk_install)"; c="$(mk_config_with_hosts localhost muvin.local)"
  out="$("$CHECK" --install-dir "$i" --config-dir "$c" 2>/dev/null)"
  rc=$?
  [ "$rc" -eq 0 ] || { echo "  expected exit 0, got $rc"; rm -rf "$i" "$c"; return 1; }
  echo "$out" | grep -qx "\[brand-cache\] skipped host=none reason=no-tunnel-ingress" \
    || { echo "  localhost/.local counted as ingress; got: $out"; rm -rf "$i" "$c"; return 1; }
  rm -rf "$i" "$c"; return 0
}

case_unfetchable_asset_is_not_silently_clean() {
  local i c stub err rc
  i="$(mk_install)"; c="$(mk_config_with_hosts operations.realagent.network)"
  # Stub that answers 502 with an empty body for every path.
  stub="$(mktemp "${TMPDIR:-/tmp}/brand-cache-curl.XXXXXX")"
  cat > "$stub" <<'STUB'
#!/usr/bin/env bash
hdr=""; out=""
while [ $# -gt 0 ]; do
  case "$1" in
    -D) hdr="$2"; shift 2 ;;
    -o) out="$2"; shift 2 ;;
    -*) shift ;;
    *) shift ;;
  esac
done
printf 'HTTP/2 502\r\n\r\n' > "$hdr"
: > "$out"
STUB
  chmod +x "$stub"
  err="$(BRAND_CACHE_CURL="$stub" "$CHECK" --install-dir "$i" --config-dir "$c" 2>&1 >/dev/null)"
  rc=$?
  [ "$rc" -eq 1 ] || { echo "  expected exit 1, got $rc"; rm -rf "$i" "$c" "$stub"; return 1; }
  echo "$err" | grep -qE "^\[brand-cache\] UNREACHABLE host=operations\.realagent\.network path=/brand/logo\.png http=502$" \
    || { echo "  no UNREACHABLE line; got: $err"; rm -rf "$i" "$c" "$stub"; return 1; }
  rm -rf "$i" "$c" "$stub"; return 0
}

case_no_assets_is_a_named_skip_not_a_clean() {
  local i c out rc
  i="$(mktemp -d "${TMPDIR:-/tmp}/brand-cache-install.XXXXXX")"; mkdir -p "$i/server/public"
  c="$(mk_config_with_hosts operations.realagent.network)"
  # bash 3.2 (macOS) errors on "${PATHS[@]}" for an empty array under `set -u`,
  # so this also pins that the loop is never entered with nothing to compare.
  out="$(/bin/bash "$CHECK" --install-dir "$i" --config-dir "$c" 2>&1)"
  rc=$?
  [ "$rc" -eq 0 ] || { echo "  expected exit 0, got $rc; got: $out"; rm -rf "$i" "$c"; return 1; }
  echo "$out" | grep -qx "\[brand-cache\] skipped host=operations.realagent.network reason=no-brand-assets" \
    || { echo "  no named skip for an empty asset list; got: $out"; rm -rf "$i" "$c"; return 1; }
  # files=0 must never be emitted: the task's own pinning exists so an empty
  # comparison cannot read as a pass.
  echo "$out" | grep -q "files=0" \
    && { echo "  emitted files=0, which reads as a pass"; rm -rf "$i" "$c"; return 1; }
  rm -rf "$i" "$c"; return 0
}

case_alias_only_install_is_checked_not_skipped() {
  local i c stub edge out rc
  i="$(mk_install)"; c="$(mk_config_alias_only)"
  edge="$(mktemp -d "${TMPDIR:-/tmp}/brand-cache-edge.XXXXXX")"
  cp "$i/server/public/brand/"* "$edge/"
  stub="$(mk_curl_stub "$edge")"
  out="$(BRAND_CACHE_CURL="$stub" "$CHECK" --install-dir "$i" --config-dir "$c" 2>/dev/null)"
  rc=$?
  [ "$rc" -eq 0 ] || { echo "  expected exit 0, got $rc"; rm -rf "$i" "$c" "$edge" "$stub"; return 1; }
  # An install with an alias edge and no ingress row does have an edge that can
  # diverge, so reporting `skipped` there would read as nothing-to-check on the
  # one state the skip wording promises it is not.
  echo "$out" | grep -qx "\[brand-cache\] clean host=public.realagent.app files=2" \
    || { echo "  alias-only install was not checked; got: $out"; rm -rf "$i" "$c" "$edge" "$stub"; return 1; }
  rm -rf "$i" "$c" "$edge" "$stub"; return 0
}

case_brand_defaults_css_is_not_fetched() {
  local i c stub edge out rc
  i="$(mk_install)"; c="$(mk_config_with_hosts admin.realagent.network public.realagent.network)"
  edge="$(mktemp -d "${TMPDIR:-/tmp}/brand-cache-edge.XXXXXX")"
  cp "$i/server/public/brand/"* "$edge/"
  # No brand-defaults.css at the edge. The gate at server/index.ts:1311-1322
  # exempts /brand/ but not /brand-defaults.css, so through an admin-gated host
  # that path answers with a login page at status 200 — hashing that against
  # the stylesheet would be a permanent false STALE with no cache involved.
  stub="$(mk_curl_stub "$edge")"
  out="$(BRAND_CACHE_CURL="$stub" "$CHECK" --install-dir "$i" --config-dir "$c" 2>/dev/null)"
  rc=$?
  [ "$rc" -eq 0 ] || { echo "  expected exit 0, got $rc"; rm -rf "$i" "$c" "$edge" "$stub"; return 1; }
  echo "$out" | grep -qx "\[brand-cache\] clean host=admin.realagent.network files=2" \
    || { echo "  expected only the two /brand/ files; got: $out"; rm -rf "$i" "$c" "$edge" "$stub"; return 1; }
  rm -rf "$i" "$c" "$edge" "$stub"; return 0
}

run_case "clean install reports clean with a pinned file count" case_clean_install_reports_clean
run_case "stale edge reports STALE on stderr and exits 1" case_stale_edge_reports_stale_on_stderr
run_case "no tunnel ingress reports skipped and exits 0" case_no_tunnel_reports_skipped
run_case "localhost/.local-only ingress counts as no tunnel" case_localhost_only_ingress_is_no_tunnel
run_case "an unfetchable asset is reported, never counted clean" case_unfetchable_asset_is_not_silently_clean
run_case "an empty asset list is a named skip, never files=0" case_no_assets_is_a_named_skip_not_a_clean
run_case "an alias-only install is checked, not skipped" case_alias_only_install_is_checked_not_skipped
run_case "brand-defaults.css is not fetched through a gated host" case_brand_defaults_css_is_not_fetched

echo ""
echo "PASS=$PASS FAIL=$FAIL"
[ "$FAIL" -eq 0 ]
