#!/usr/bin/env bash
# ==============================================================================
# bindu.protocol — Sovereign AI Mesh Client & QoS Injector Installer
# Public Endpoint: https://bindu.cloud/protocol/install
# Target: macOS (Apple Silicon / Intel), Linux (Ubuntu, Debian, Fedora, Arch), WSL2
# ==============================================================================
set -euo pipefail

HUB_URL="${BINDU_HUB_URL:-https://bindu.cloud}"
DEFAULT_MODE="${BINDU_QOS_PRESET:-${BINDU_DEFAULT_MODE:-interactive_dev}}"
INSTALL_DIR="${HOME}/.local/bin"
CONFIG_DIR="${HOME}/.config/bindu"

echo "============================================================"
echo "  bindu.protocol • Sovereign AI Mesh Client Setup"
echo "  Control Plane: ${HUB_URL}"
echo "  Initial QoS Mode: ${DEFAULT_MODE}"
echo "============================================================"

# 1. OS & Architecture Detection
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"
HOSTNAME_VAL="$(hostname 2>/dev/null || echo 'sovereign-node')"
echo "[1/4] Detected environment: ${OS} (${ARCH}) on ${HOSTNAME_VAL}"

# 2. Prepare Config & Bin Directory
mkdir -p "${INSTALL_DIR}"
mkdir -p "${CONFIG_DIR}"
if [ -n "${BINDU_CA_CERT:-}" ]; then
  [ -r "${BINDU_CA_CERT}" ] || { echo "Cannot read Bindu CA certificate" >&2; exit 1; }
  cp "${BINDU_CA_CERT}" "${CONFIG_DIR}/ca.crt"
  chmod 600 "${CONFIG_DIR}/ca.crt"
fi

# 3. Create or Validate Local Ed25519 Sovereign Keypair
KEY_FILE="${CONFIG_DIR}/sovereign_identity.key"
PUB_FILE="${CONFIG_DIR}/sovereign_identity.pub"

if [ ! -f "${KEY_FILE}" ]; then
  echo "[2/4] Generating local Ed25519 Sovereign Passport keypair..."
  if command -v openssl >/dev/null 2>&1; then
    openssl genpkey -algorithm ed25519 -out "${KEY_FILE}" 2>/dev/null
    openssl pkey -in "${KEY_FILE}" -pubout -out "${PUB_FILE}" 2>/dev/null
    chmod 600 "${KEY_FILE}"
    echo "      Keypair created at ${CONFIG_DIR}/sovereign_identity"
  else
    echo "      [INFO] Key generation deferred to client CLI runtime"
  fi
else
  echo "[2/4] Existing Sovereign Passport keypair found at ${KEY_FILE}"
fi

# 3b. Write Local Sovereign Protocol Configuration (protocol.json)
PROTOCOL_JSON="${CONFIG_DIR}/protocol.json"
PUB_HEX=""
if [ -f "${PUB_FILE}" ]; then
  PUB_HEX="$(grep -v '^---' "${PUB_FILE}" | tr -d '\n' || true)"
fi
cat << EOF > "${PROTOCOL_JSON}"
{
  "hubUrl": "${HUB_URL}",
  "presetMode": "${DEFAULT_MODE}",
  "hostname": "${HOSTNAME_VAL}",
  "os": "${OS}",
  "arch": "${ARCH}",
  "publicKeyPemBase64": "${PUB_HEX}",
  "installedAt": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
}
EOF

# 4. Generate bindu-protocol Client CLI Wrapper
CLIENT_BIN="${INSTALL_DIR}/bindu-protocol"
cat << 'EOF' > "${CLIENT_BIN}"
#!/usr/bin/env bash
# bindu.protocol Client CLI
CONFIG_FILE="${HOME}/.config/bindu/protocol.json"
DEFAULT_HUB="https://bindu.cloud"
if [ -f "${CONFIG_FILE}" ] && command -v grep >/dev/null 2>&1; then
  SAVED_HUB="$(grep -o '"hubUrl":[[:space:]]*"[^"]*"' "${CONFIG_FILE}" | cut -d'"' -f4 || true)"
  if [ -n "${SAVED_HUB}" ]; then
    DEFAULT_HUB="${SAVED_HUB}"
  fi
fi
HUB="${BINDU_HUB_URL:-${DEFAULT_HUB}}"
CURL_OPTS=(-fsSL)
CA_CERT="${BINDU_CA_CERT:-${HOME}/.config/bindu/ca.crt}"
if [ -f "${CA_CERT}" ]; then CURL_OPTS+=(--cacert "${CA_CERT}"); fi
CMD="${1:-widget}"

case "${CMD}" in
  widget)
    echo "Opening bindu.protocol Client Widget..."
    if command -v open >/dev/null 2>&1; then
      open "${HUB}/protocol/widget"
    elif command -v xdg-open >/dev/null 2>&1; then
      xdg-open "${HUB}/protocol/widget"
    else
      echo "Visit: ${HUB}/protocol/widget"
    fi
    ;;
  config)
    curl "${CURL_OPTS[@]}" "${HUB}/protocol/config"
    echo ""
    ;;
  mode)
    MODE="${2:-interactive_dev}"
    if [ -f "${CONFIG_FILE}" ] && command -v sed >/dev/null 2>&1; then
      sed -i.bak "s/\"presetMode\":[[:space:]]*\"[^\"]*\"/\"presetMode\": \"${MODE}\"/" "${CONFIG_FILE}" && rm -f "${CONFIG_FILE}.bak"
    fi
    curl "${CURL_OPTS[@]}" -X POST "${HUB}/protocol/config" \
      -H "Content-Type: application/json" \
      -H "Origin: ${HUB}" \
      -d "{\"presetMode\":\"${MODE}\"}"
    echo ""
    ;;
  status)
    curl "${CURL_OPTS[@]}" "${HUB}/protocol/config"
    echo ""
    ;;
  submit)
    PROMPT="${2:-}"
    if [ -z "${PROMPT}" ]; then
      echo "Usage: bindu-protocol submit <prompt> [presetMode]"
      exit 1
    fi
    PRESET="${3:-interactive_dev}"
    curl "${CURL_OPTS[@]}" -X POST "${HUB}/protocol/tasks/submit" \
      -H "Content-Type: application/json" \
      -H "Origin: ${HUB}" \
      -d "{\"prompt\":\"${PROMPT}\",\"presetMode\":\"${PRESET}\"}"
    echo ""
    ;;
  *)
    echo "bindu.protocol CLI"
    echo "Commands:"
    echo "  bindu-protocol widget         - Launch client widget UI"
    echo "  bindu-protocol config         - Show active QoS config"
    echo "  bindu-protocol mode <preset>  - Set QoS mode (interactive_dev | balanced_sprint | compute_contributor)"
    echo "  bindu-protocol status         - Check fleet queue status"
    echo "  bindu-protocol submit <prompt>- Submit task into QoS pipeline"
    ;;
esac
EOF

chmod +x "${CLIENT_BIN}"
echo "[3/4] Client CLI installed to ${CLIENT_BIN}"

# Sync initial mode with Hub Control Plane (best-effort)
CURL_INIT_OPTS=(-fsSL)
if [ -f "${CONFIG_DIR}/ca.crt" ]; then CURL_INIT_OPTS+=(--cacert "${CONFIG_DIR}/ca.crt"); fi
curl "${CURL_INIT_OPTS[@]}" -m 5 -X POST "${HUB_URL}/protocol/config" \
  -H "Content-Type: application/json" \
  -H "Origin: ${HUB_URL}" \
  -d "{\"presetMode\":\"${DEFAULT_MODE}\"}" >/dev/null 2>&1 || true

# 5. Check PATH
if [[ ":$PATH:" != *":${INSTALL_DIR}:"* ]]; then
  echo "[INFO] ${INSTALL_DIR} is not in your PATH."
  echo "       Add it to your profile: export PATH="\$HOME/.local/bin:\$PATH""
fi

echo "[4/4] Installation Complete!"
echo "------------------------------------------------------------"
echo "  Config saved to: ${PROTOCOL_JSON}"
echo "  Run 'bindu-protocol widget' to open the client tray UI."
echo "  Active QoS preset: ${DEFAULT_MODE}"
echo "============================================================"
