#!/usr/bin/env bash
# read-brand-json.sh — brand.json reader + LocalBusiness bootstrap helpers.
#
# Sourced by setup-account.sh and seed-neo4j.sh. Three functions:
#
#   read_brand_json_key <brand.json path> <key>
#     Sets the global BRAND_JSON_VALUE to the value at <key>, or empty when
#     the file is missing, the key is absent, or the value is JSON null.
#     Loud-fails (exit 1) on JSON parse error so a malformed brand.json
#     never silently propagates as a default — install.log carries the
#     reason. Output via global rather than $() because bash `var=$(cmd)`
#     does not propagate the substitution's exit status under `set -e`.
#
#   derive_business_type <brand.json#vertical value>
#     Strips a leading "schema-" prefix to produce the bare slug stored on
#     LocalBusiness.businessType (`resolve-active-vertical.ts` prepends
#     "schema-" when reading back). Returns the bare slug if the prefix is
#     absent, empty for empty input. Echoes to stdout.
#
#   business_type_cypher <bare slug>
#     Emits a Cypher literal: a single-quoted string for a non-empty slug
#     or the bare keyword null for empty input. Echoes to stdout.
#     Used to interpolate businessType into the LocalBusiness MERGE.

# shellcheck shell=bash

read_brand_json_key() {
  local brand_json="$1"
  local key="$2"
  BRAND_JSON_VALUE=""
  [ -f "$brand_json" ] || return 0
  if ! BRAND_JSON_VALUE=$(python3 - "$brand_json" "$key" <<'PY'
import json, sys
path = sys.argv[1]
key = sys.argv[2]
try:
    with open(path) as f:
        data = json.load(f)
except json.JSONDecodeError as e:
    sys.stderr.write(
        f"  [install-invariant] brand-json-read result=failed "
        f"reason=parse-error file={path} detail={e}\n"
    )
    sys.exit(1)
value = data.get(key)
print("" if value is None else value)
PY
); then
    exit 1
  fi
}

derive_business_type() {
  local vertical="$1"
  if [ -z "$vertical" ]; then
    echo ""
    return 0
  fi
  echo "${vertical#schema-}"
}

business_type_cypher() {
  local slug="$1"
  if [ -z "$slug" ]; then
    echo "null"
  else
    echo "'$slug'"
  fi
}

#   cypher_string_literal <value>
#     Emits a Cypher literal for an arbitrary string: the bare keyword null
#     for empty input, otherwise the value wrapped in single quotes with
#     backslashes and single quotes escaped. Unlike business_type_cypher
#     (which quotes a closed-enum slug that needs no escaping), this is for
#     free-text values such as brand.json#productName, so it escapes to keep
#     an apostrophe (e.g. "O'Brien") from breaking the MERGE.
cypher_string_literal() {
  local s="$1"
  if [ -z "$s" ]; then
    echo "null"
    return 0
  fi
  local q="'"
  s="${s//\\/\\\\}"   # backslash -> two backslashes
  s="${s//$q/\\$q}"   # single quote -> backslash + quote
  printf "%s\n" "$q$s$q"
}
