#!/usr/bin/env bash
# Read-only deploy parity check for the 110 cold-start monitor.

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
REMOTE="${REMOTE:-wooo@192.168.0.110}"
SSH_BATCH_MODE="${SSH_BATCH_MODE:-yes}"
SSH_STRICT_HOST_KEY_CHECKING="${SSH_STRICT_HOST_KEY_CHECKING:-accept-new}"
REMOTE_COMMAND_TIMEOUT_SECONDS="${REMOTE_COMMAND_TIMEOUT_SECONDS:-45}"
PROMETHEUS_URL="${PROMETHEUS_URL:-http://192.168.0.110:9090}"

ssh_opts=(
  -o BatchMode="$SSH_BATCH_MODE"
  -o ConnectTimeout=6
  -o ConnectionAttempts=1
  -o ServerAliveInterval=5
  -o ServerAliveCountMax=1
  -o StrictHostKeyChecking="$SSH_STRICT_HOST_KEY_CHECKING"
)

local_sha256() {
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | awk '{print $1}'
  else
    shasum -a 256 "$1" | awk '{print $1}'
  fi
}

remote_sha256() {
  remote_read "sha256sum '$1' 2>/dev/null | awk '{print \$1}'"
}

remote_read() {
  local command="$1"
  local quoted_command=""
  printf -v quoted_command '%q' "$command"
  ssh "${ssh_opts[@]}" "$REMOTE" "if command -v timeout >/dev/null 2>&1; then timeout ${REMOTE_COMMAND_TIMEOUT_SECONDS}s bash -lc ${quoted_command}; else bash -lc ${quoted_command}; fi"
}

require_same_hash() {
  local local_path="$1"
  local remote_path="$2"
  local label="$3"
  local local_hash remote_hash

  local_hash="$(local_sha256 "$ROOT_DIR/$local_path")"
  remote_hash="$(remote_sha256 "$remote_path")"
  if [ -z "$remote_hash" ]; then
    echo "BLOCKED $label missing on $REMOTE: $remote_path" >&2
    return 1
  fi
  if [ "$local_hash" != "$remote_hash" ]; then
    echo "BLOCKED $label hash mismatch local=$local_hash remote=$remote_hash" >&2
    return 1
  fi
  echo "OK $label hash matches $REMOTE"
}

require_remote_pattern() {
  local pattern="$1"
  local path="$2"
  local label="$3"
  if remote_read "grep -Fq '$pattern' '$path'"; then
    echo "OK $label"
  else
    echo "BLOCKED $label missing in $path" >&2
    return 1
  fi
}

report_cold_start_alerts() {
  PROMETHEUS_URL="$PROMETHEUS_URL" python3 - <<'PY'
import json
import os
import urllib.parse
import urllib.request

base_url = os.environ["PROMETHEUS_URL"].rstrip("/")
expr = 'ALERTS{alertname=~"ColdStart.*",alertstate="firing"}'
try:
    url = base_url + "/api/v1/query?" + urllib.parse.urlencode({"query": expr})
    payload = json.load(urllib.request.urlopen(url, timeout=8))
    rows = payload.get("data", {}).get("result") if payload.get("status") == "success" else []
except Exception as exc:  # noqa: BLE001
    print(f"COLD_START_ALERT_REPORT query_error={exc}")
else:
    rows = rows or []
    names = sorted({(row.get("metric") or {}).get("alertname", "unknown") for row in rows})
    print(
        "COLD_START_ALERT_REPORT "
        f"firing_count={len(rows)} "
        f"alertnames={','.join(names) if names else 'none'}"
    )
PY
}

report_runtime_state() {
  remote_read "awk '
    /awoooi_cold_start_monitor_up/ {monitor_up=\$NF}
    /awoooi_cold_start_warn_gates/ {warn=\$NF}
    /awoooi_cold_start_blocked_gates/ {blocked=\$NF}
    /awoooi_cold_start_last_result.*result=\"green\"/ {green=\$NF}
    /awoooi_cold_start_last_result.*result=\"blocked\"/ {blocked_state=\$NF}
    END {
      printf \"COLD_START_MONITOR_RUNTIME_STATE monitor_up=%s warn=%s blocked=%s green=%s blocked_state=%s\\n\", monitor_up+0, warn+0, blocked+0, green+0, blocked_state+0
    }
  ' /home/wooo/node_exporter_textfiles/cold_start_recovery.prom"
}

require_same_hash \
  "scripts/reboot-recovery/full-stack-cold-start-check.sh" \
  "/home/wooo/scripts/full-stack-cold-start-check.sh" \
  "full-stack-cold-start-check.sh"

require_same_hash \
  "scripts/reboot-recovery/cold-start-textfile-exporter.sh" \
  "/home/wooo/scripts/cold-start-textfile-exporter.sh" \
  "cold-start-textfile-exporter.sh"

require_same_hash \
  "scripts/reboot-recovery/momo-drive-token-source-recovery-preflight.sh" \
  "/home/wooo/scripts/momo-drive-token-source-recovery-preflight.sh" \
  "momo-drive-token-source-recovery-preflight.sh"

require_remote_pattern \
  "StrictHostKeyChecking" \
  "/home/wooo/scripts/full-stack-cold-start-check.sh" \
  "110 deployed check script carries SSH host-key policy"

require_remote_pattern \
  'awoooi_cold_start_monitor_up{host="110",scope="110_120_121_188",mode="read_only"} 1' \
  "/home/wooo/node_exporter_textfiles/cold_start_recovery.prom" \
  "110 cold-start monitor produced parseable metrics"

report_runtime_state
report_cold_start_alerts

echo "COLD_START_MONITOR_DEPLOY_PARITY_OK"
