#!/usr/bin/env bash
# =============================================================================
# publish-super-certifier.sh
#
# Calls the Super Certifier Admin API to:
#   1. Publish the Super Certifier DID Document to the IOTA Tangle
#   2. Fetch the list of active certifier DIDs
#
# Then patches .env with all derived values and restarts CVS and
# certifier-service so the new values take effect immediately:
#   - CVS_SUPER_CERTIFIER_DID  — Super Certifier DID (trusted root for CVS)
#   - SUPER_CERTIFIER_DID      — same, for certifier-service reference
#   - CVS_CERTIFIER_DIDS       — comma-separated list of trusted certifier DIDs
#   - CERTIFIER_DID            — first active certifier DID (for certifier-service)
#
# Prerequisites:
#   - docker compose services are running (super-certifier-admin, cvs,
#     certifier-service)
#   - At least one certifier must be in 'active' state before publishing
#   - IOTA_IDENTITY_PKG_ID must be set in .env and the Move package deployed
#
# Usage:
#   ./scripts/publish-super-certifier.sh
#   ./scripts/publish-super-certifier.sh --sca-url http://localhost:8083
# =============================================================================

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

# ---------------------------------------------------------------------------
# Parse arguments
# ---------------------------------------------------------------------------

SCA_URL="http://localhost:8083"

for arg in "$@"; do
  case $arg in
    --sca-url)
      shift
      SCA_URL="${1}"
      shift
      ;;
    --sca-url=*)
      SCA_URL="${arg#*=}"
      shift
      ;;
  esac
done

ENV_FILE="${REPO_ROOT}/.env"

echo "==> Publishing Super Certifier DID Document..."
echo "    SCA URL: ${SCA_URL}"
echo ""

# ---------------------------------------------------------------------------
# Call the publish endpoint
# ---------------------------------------------------------------------------

HTTP_RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "${SCA_URL}/v1/publish" \
  -H "Content-Type: application/json" 2>&1) || {
  echo "ERROR: Could not reach Super Certifier Admin at ${SCA_URL}."
  echo "       Are services running? Try: docker compose up -d"
  exit 1
}

HTTP_BODY=$(echo "${HTTP_RESPONSE}" | sed '$d')
HTTP_CODE=$(echo "${HTTP_RESPONSE}" | tail -n 1)

if [ "${HTTP_CODE}" != "200" ]; then
  echo "ERROR: Publish request failed (HTTP ${HTTP_CODE})."
  echo "       Response: ${HTTP_BODY}"
  echo ""
  echo "  Common causes:"
  echo "    - No active certifiers yet (complete Steps 8A+8B first)"
  echo "    - IOTA_IDENTITY_PKG_ID not set or wrong (run deploy-identity-pkg.sh)"
  echo "    - Gas wallet not funded (run fund-services.sh)"
  exit 1
fi

# ---------------------------------------------------------------------------
# Extract the DID from the response
# ---------------------------------------------------------------------------

SUPER_DID=$(echo "${HTTP_BODY}" | python3 -c "
import sys, json
data = json.load(sys.stdin)
print(data['super_did'])
" 2>/dev/null || echo "")

CERTIFIER_COUNT=$(echo "${HTTP_BODY}" | python3 -c "
import sys, json
data = json.load(sys.stdin)
print(data.get('certifier_count', '?'))
" 2>/dev/null || echo "?")

if [ -z "${SUPER_DID}" ]; then
  echo "ERROR: Could not extract 'super_did' from response."
  echo "       Response: ${HTTP_BODY}"
  exit 1
fi

echo "  Super Certifier DID: ${SUPER_DID}"
echo "  Certifiers linked:   ${CERTIFIER_COUNT}"
echo ""

# ---------------------------------------------------------------------------
# Fetch active certifier DIDs from the SCA certifiers list
# ---------------------------------------------------------------------------

echo "==> Fetching active certifier DIDs..."
CERTIFIERS_JSON=$(curl -sf "${SCA_URL}/v1/certifiers" 2>/dev/null || echo "[]")

CERTIFIER_DIDS=$(echo "${CERTIFIERS_JSON}" | python3 -c "
import sys, json
data = json.load(sys.stdin)
dids = [c['did'] for c in data if c.get('status') == 'active' and c.get('did')]
print(','.join(dids))
" 2>/dev/null || echo "")

CERTIFIER_DID_FIRST=$(echo "${CERTIFIER_DIDS}" | cut -d, -f1)

if [ -n "${CERTIFIER_DIDS}" ]; then
  echo "  Active certifier DID(s): ${CERTIFIER_DIDS}"
else
  echo "  WARNING: No active certifier DIDs found — CVS_CERTIFIER_DIDS will not be patched."
fi
echo ""

# ---------------------------------------------------------------------------
# Patch .env
# ---------------------------------------------------------------------------

if [ ! -f "${ENV_FILE}" ]; then
  echo "WARNING: No .env file found at ${ENV_FILE}."
  echo "         Copy these values manually:"
  echo ""
  echo "         CVS_SUPER_CERTIFIER_DID=${SUPER_DID}"
  echo "         SUPER_CERTIFIER_DID=${SUPER_DID}"
  [ -n "${CERTIFIER_DIDS}" ] && echo "         CVS_CERTIFIER_DIDS=${CERTIFIER_DIDS}"
  [ -n "${CERTIFIER_DID_FIRST}" ] && echo "         CERTIFIER_DID=${CERTIFIER_DID_FIRST}"
  exit 0
fi

patch_env_var() {
  local key="$1"
  local value="$2"
  if grep -q "^${key}=" "${ENV_FILE}"; then
    if sed --version 2>/dev/null | grep -q GNU; then
      sed -i "s|^${key}=.*|${key}=${value}|" "${ENV_FILE}"
    else
      sed -i '' "s|^${key}=.*|${key}=${value}|" "${ENV_FILE}"
    fi
  else
    echo "" >> "${ENV_FILE}"
    echo "${key}=${value}" >> "${ENV_FILE}"
  fi
}

echo "==> Patching .env ..."
patch_env_var "CVS_SUPER_CERTIFIER_DID" "${SUPER_DID}"
patch_env_var "SUPER_CERTIFIER_DID" "${SUPER_DID}"
echo "    CVS_SUPER_CERTIFIER_DID=${SUPER_DID}"
echo "    SUPER_CERTIFIER_DID=${SUPER_DID}"

if [ -n "${CERTIFIER_DIDS}" ]; then
  patch_env_var "CVS_CERTIFIER_DIDS" "${CERTIFIER_DIDS}"
  echo "    CVS_CERTIFIER_DIDS=${CERTIFIER_DIDS}"
fi

if [ -n "${CERTIFIER_DID_FIRST}" ]; then
  patch_env_var "CERTIFIER_DID" "${CERTIFIER_DID_FIRST}"
  echo "    CERTIFIER_DID=${CERTIFIER_DID_FIRST}"
fi
echo ""

# ---------------------------------------------------------------------------
# Restart CVS and certifier-service
# ---------------------------------------------------------------------------

echo "==> Recreating CVS and certifier-service to apply new .env values..."
docker compose -f "${REPO_ROOT}/docker-compose.yml" up -d --no-build cvs certifier-service 2>&1 | sed 's/^/    /' || \
  echo "    WARNING: recreate failed — run: docker compose up -d --no-build cvs certifier-service"

# ANSI colors
_BOLD='\033[1m'
_GREEN='\033[0;32m'
_CYAN='\033[0;36m'
_WHITE='\033[1;37m'
_DIM='\033[2m'
_RESET='\033[0m'

_W=127
_line() {
    local text="$1"
    local visible
    visible=$(echo -e "$text" | sed 's/\x1b\[[0-9;]*m//g')
    local len=${#visible}
    local pad=$((_W - len))
    if [ $pad -lt 0 ]; then pad=0; fi
    printf "${_GREEN}║${_RESET}%b%*s${_GREEN}║${_RESET}\n" "$text" "$pad" ""
}
_TOP="${_GREEN}╔$(printf '═%.0s' $(seq 1 $_W))╗${_RESET}"
_MID="${_GREEN}╠$(printf '═%.0s' $(seq 1 $_W))╣${_RESET}"
_BOT="${_GREEN}╚$(printf '═%.0s' $(seq 1 $_W))╝${_RESET}"

echo ""
echo -e "$_TOP"
_line ""
_line "  ${_WHITE}${_BOLD}Super Certifier DID published${_RESET}"
_line ""
echo -e "$_MID"
_line ""
_line "  ${_BOLD}Super Certifier DID:${_RESET}"
_line "  ${_CYAN}${SUPER_DID}${_RESET}"
if [ -n "${CERTIFIER_DIDS}" ]; then
_line ""
_line "  ${_BOLD}Certifier DID(s):${_RESET}"
IFS=',' read -ra _CERT_ARRAY <<< "${CERTIFIER_DIDS}"
for _cdid in "${_CERT_ARRAY[@]}"; do
  _line "  ${_CYAN}${_cdid}${_RESET}"
done
fi
_line ""
_line "  ${_DIM}CVS and certifier-service restarted with updated DIDs.${_RESET}"
_line ""
if [ -z "${WIZARD_MODE:-}" ]; then
    echo -e "$_MID"
    _line ""
    _line "  ${_BOLD}Next steps:${_RESET}"
    _line "    1. Open Agent Tester: ${_DIM}http://localhost:5176${_RESET}"
    _line "    2. Create a profile, register, and fetch content"
    _line ""
fi
echo -e "$_BOT"
