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

API_BASE_URL="${DERIOX_GUARD_API_BASE_URL:-https://guard.deriox.ro}"
PAIRING_ENDPOINT="${API_BASE_URL}/api/gateway/mini-pc/pairing-request"
STATUS_ENDPOINT="${API_BASE_URL}/api/gateway/mini-pc/approval-status"
VERSION="m8.8-pairing-cli-stub"

MODE="dry-run"
GATEWAY_UUID=""
GATEWAY_NAME="${DERIOX_GUARD_GATEWAY_NAME:-Deriox Guard Mini PC}"
CLIENT_NAME="${DERIOX_GUARD_CLIENT_NAME:-}"
LOCATION_NAME="${DERIOX_GUARD_LOCATION_NAME:-}"

while [ $# -gt 0 ]; do
  case "$1" in
    --pair) MODE="pair"; shift ;;
    --status) MODE="status"; shift ;;
    --show-payload) MODE="show-payload"; shift ;;
    --gateway-uuid) GATEWAY_UUID="${2:-}"; shift 2 ;;
    --gateway-name) GATEWAY_NAME="${2:-}"; shift 2 ;;
    --client-name) CLIENT_NAME="${2:-}"; shift 2 ;;
    --location-name) LOCATION_NAME="${2:-}"; shift 2 ;;
    --api-base-url) API_BASE_URL="${2:-}"; PAIRING_ENDPOINT="${API_BASE_URL}/api/gateway/mini-pc/pairing-request"; STATUS_ENDPOINT="${API_BASE_URL}/api/gateway/mini-pc/approval-status"; shift 2 ;;
    --help|-h)
      echo "Deriox Guard Pairing CLI - ${VERSION}"
      echo ""
      echo "Dry-run implicit:"
      echo "  ./deriox-guard-pairing-cli.sh"
      echo ""
      echo "Preview payload:"
      echo "  ./deriox-guard-pairing-cli.sh --show-payload --gateway-name \"Mini PC\" --client-name \"Client\" --location-name \"Locatie\""
      echo ""
      echo "Trimite pairing metadata-only:"
      echo "  ./deriox-guard-pairing-cli.sh --pair --gateway-name \"Mini PC\" --client-name \"Client\" --location-name \"Locatie\""
      echo ""
      echo "Verifică aprobare:"
      echo "  ./deriox-guard-pairing-cli.sh --status --gateway-uuid \"GW-...\""
      exit 0
      ;;
    *)
      echo "Argument necunoscut: $1"
      echo "Rulează cu --help"
      exit 1
      ;;
  esac
done

detect_os() {
  if command -v lsb_release >/dev/null 2>&1; then
    lsb_release -ds 2>/dev/null | tr -d '"'
  elif [ -f /etc/os-release ]; then
    . /etc/os-release
    echo "${PRETTY_NAME:-Linux}"
  else
    echo "Linux"
  fi
}

fingerprint_hash() {
  HOST="$(hostname 2>/dev/null || echo unknown-host)"
  MACHINE_ID=""
  if [ -f /etc/machine-id ]; then
    MACHINE_ID="$(cat /etc/machine-id 2>/dev/null || true)"
  fi
  CPU="$(uname -m 2>/dev/null || echo unknown-cpu)"
  RAW="${HOST}|${MACHINE_ID}|${CPU}|deriox-guard"
  printf "%s" "$RAW" | sha256sum | awk '{print $1}'
}

DEVICE_HASH="$(fingerprint_hash)"
OS_LABEL="$(detect_os)"
LOCAL_IP="$(hostname -I 2>/dev/null | awk '{print $1}' || true)"

if [ -z "$GATEWAY_UUID" ]; then
  GATEWAY_UUID="GW-$(printf "%s" "${DEVICE_HASH}" | cut -c1-16)"
fi

payload() {
  cat <<JSON
{
  "gateway_uuid": "${GATEWAY_UUID}",
  "gateway_name": "${GATEWAY_NAME}",
  "client_name": "${CLIENT_NAME}",
  "location_name": "${LOCATION_NAME}",
  "device_fingerprint_hash": "${DEVICE_HASH}",
  "software_version": "${VERSION}",
  "os_label": "${OS_LABEL}",
  "local_ip_hint": "${LOCAL_IP}",
  "security": {
    "outbound_only": true,
    "metadata_only": true,
    "camera_password_included": false,
    "stream_link_included": false,
    "media_included": false,
    "billing_enabled": false,
    "camera_actions_enabled": false
  }
}
JSON
}

echo "=================================================="
echo "Deriox Guard Pairing CLI - ${VERSION}"
echo "=================================================="
echo "Mode: ${MODE}"
echo "API: ${API_BASE_URL}"
echo "Gateway UUID: ${GATEWAY_UUID}"
echo "Gateway name: ${GATEWAY_NAME}"
echo "Client: ${CLIENT_NAME:-necompletat}"
echo "Location: ${LOCATION_NAME:-necompletat}"
echo "OS: ${OS_LABEL}"
echo "Security: metadata-only, no camera passwords, no streams, no media, no billing"
echo ""

case "$MODE" in
  dry-run)
    echo "Dry-run. Nu trimit nimic către server."
    echo "Pentru payload: --show-payload"
    echo "Pentru pairing: --pair"
    ;;
  show-payload)
    payload
    ;;
  pair)
    if ! command -v curl >/dev/null 2>&1; then
      echo "EROARE: curl nu este instalat."
      exit 1
    fi
    echo "Trimit pairing request metadata-only..."
    payload | curl -fsSL -X POST "$PAIRING_ENDPOINT" -H "Content-Type: application/json" --data-binary @-
    echo ""
    echo "Pairing request trimis. Gateway-ul rămâne în pending până la aprobarea din Admin Deriox."
    ;;
  status)
    if ! command -v curl >/dev/null 2>&1; then
      echo "EROARE: curl nu este instalat."
      exit 1
    fi
    curl -fsSL "${STATUS_ENDPOINT}?gateway_uuid=${GATEWAY_UUID}"
    echo ""
    ;;
esac