#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
ROUTE_MATRIX_ROOT="${ROUTE_MATRIX_ROOT:-$ROOT_DIR/artifacts/phase2-routing-matrix}"

require_var() {
  local name="$1"
  if [[ -z "${!name:-}" ]]; then
    echo "missing required env: $name" >&2
    exit 1
  fi
}

ensure_artifact_dir() {
  mkdir -p "$ARTIFACT_DIR"
}

save_json() {
  local name="$1"
  local payload="$2"
  ensure_artifact_dir
  printf '%s\n' "$payload" > "$ARTIFACT_DIR/$name.json"
}

save_text() {
  local name="$1"
  local payload="$2"
  ensure_artifact_dir
  printf '%s\n' "$payload" > "$ARTIFACT_DIR/$name"
}

json_get_file() {
  local file="$1"
  local key="$2"
  python3 - "$file" "$key" <<'PY'
import json
import sys

file_path, key = sys.argv[1:3]
with open(file_path, 'r', encoding='utf-8') as fh:
    value = json.load(fh)
for part in key.split('.'):
    if isinstance(value, dict):
        value = value.get(part)
    else:
        value = None
        break
if value is None:
    raise SystemExit(2)
if isinstance(value, (dict, list)):
    print(json.dumps(value, ensure_ascii=False))
else:
    print(value)
PY
}

crm_auth_init() {
  require_var CRM_BASE

  if [[ -n "${CRM_ADMIN_TOKEN:-}" ]]; then
    crm_token="$CRM_ADMIN_TOKEN"
    crm_cookie_jar=""
    return 0
  fi

  if [[ -n "${CRM_COOKIE_JAR:-}" ]]; then
    crm_cookie_jar="$CRM_COOKIE_JAR"
  else
    crm_cookie_jar="$(mktemp /tmp/route-matrix-cookie.XXXXXX.jar)"
  fi
  rm -f "$crm_cookie_jar"

  require_var CRM_ADMIN_USERNAME
  require_var CRM_ADMIN_PASSWORD

  local login_payload
  login_payload="$(python3 - "$CRM_ADMIN_USERNAME" "$CRM_ADMIN_PASSWORD" <<'PY'
import json
import sys
username, password = sys.argv[1:3]
print(json.dumps({"username": username, "password": password}, ensure_ascii=False))
PY
)"

  curl -fsS \
    -c "$crm_cookie_jar" \
    -b "$crm_cookie_jar" \
    -H 'Content-Type: application/json' \
    -X POST \
    "${CRM_BASE%/}/api/admin/session/login" \
    -d "$login_payload" > /dev/null
  crm_token=""
}

crm_curl_json() {
  local method="$1"
  local path="$2"
  local payload="${3:-}"
  local -a curl_args
  curl_args=(-fsS -X "$method")
  if [[ -n "${crm_token:-}" ]]; then
    curl_args+=(-H "Authorization: Bearer $crm_token")
  elif [[ -n "${crm_cookie_jar:-}" ]]; then
    curl_args+=(-b "$crm_cookie_jar" -c "$crm_cookie_jar")
  else
    echo "missing CRM auth: set CRM_ADMIN_TOKEN or CRM_ADMIN_USERNAME/CRM_ADMIN_PASSWORD" >&2
    exit 2
  fi
  if [[ -n "$payload" ]]; then
    curl_args+=(
      -H 'Content-Type: application/json'
      "${CRM_BASE%/}${path}"
      -d "$payload"
    )
  else
    curl_args+=("${CRM_BASE%/}${path}")
  fi
  curl "${curl_args[@]}"
}

curl_status_to_file() {
  local url="$1"
  local file="$2"
  ensure_artifact_dir
  curl -fsS "$url" -o "$file"
}

timestamp_token() {
  date +%s
}
