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

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
PLATFORM_REPO="$(cd -- "${SCRIPT_DIR}/../.." && pwd)"
NAS_ROOT="${NAS_ROOT:-/Volumes/docker/nodedc-platform}"
GATEWAY_REPO="${GATEWAY_REPO:-${PLATFORM_REPO}/../../data/NODEDC_TASKMANAGER_CODEXAPI}"
ENGINE_REPO="${ENGINE_REPO:-${PLATFORM_REPO}/../NODEDC_ENGINE_INFRA}"

NAS_PLATFORM_ENV="${NAS_PLATFORM_ENV:-${NAS_ROOT}/platform/.env.synology}"
NAS_GATEWAY_ENV="${NAS_GATEWAY_ENV:-${NAS_ROOT}/ops-agents/.env}"

passed=0
failed=0
warnings=0

section() {
  printf '\n== %s ==\n' "$1"
}

pass() {
  passed=$((passed + 1))
  printf 'PASS %s\n' "$1"
}

fail() {
  failed=$((failed + 1))
  printf 'FAIL %s\n' "$1" >&2
}

warn() {
  warnings=$((warnings + 1))
  printf 'WARN %s\n' "$1" >&2
}

read_env() {
  local file="$1"
  local key="$2"
  [[ -f "${file}" ]] || return 0
  awk -F= -v key="${key}" '
    $0 ~ "^[[:space:]]*#" { next }
    $1 == key {
      value = substr($0, index($0, "=") + 1)
      gsub(/^[[:space:]]+|[[:space:]]+$/, "", value)
      gsub(/^"|"$/, "", value)
      print value
      exit
    }
  ' "${file}"
}

require_path() {
  local path="$1"
  local label="$2"
  if [[ -e "${path}" ]]; then
    pass "${label}"
  else
    fail "${label} (missing: ${path})"
  fi
}

require_file_contains() {
  local file="$1"
  local needle="$2"
  local label="$3"
  if [[ ! -f "${file}" ]]; then
    fail "${label} (missing file: ${file})"
    return
  fi
  if grep -Fq "${needle}" "${file}"; then
    pass "${label}"
  else
    fail "${label} (missing: ${needle})"
  fi
}

require_env_value() {
  local file="$1"
  local key="$2"
  local expected="$3"
  local label="$4"
  local actual
  actual="$(read_env "${file}" "${key}" || true)"
  if [[ "${actual}" == "${expected}" ]]; then
    pass "${label}"
  else
    fail "${label} (expected ${key}=${expected}, got ${actual:-<missing>})"
  fi
}

require_env_nonempty() {
  local file="$1"
  local key="$2"
  local label="$3"
  local actual
  actual="$(read_env "${file}" "${key}" || true)"
  if [[ -n "${actual}" && "${actual}" != replace-with-* && "${actual}" != change-me-* ]]; then
    pass "${label}"
  else
    fail "${label} (${key} missing or placeholder)"
  fi
}

section "Local prerequisites"
require_path "${NAS_ROOT}" "NAS mount exists"
require_path "${GATEWAY_REPO}" "Ops Gateway repo exists"
require_path "${ENGINE_REPO}" "Engine repo exists"
require_path "${PLATFORM_REPO}/infra/scripts/check-ai-workspace-release-gates.sh" "Predeploy gate runner exists"
require_path "${PLATFORM_REPO}/infra/scripts/check-ai-workspace-config-contract.sh" "Config contract checker exists"
require_path "${PLATFORM_REPO}/infra/synology/backup-current.sh" "Synology backup script exists"
require_path "${PLATFORM_REPO}/infra/synology/apply-current-runtime.sh" "Synology apply script exists"
require_path "${PLATFORM_REPO}/infra/synology/verify-current-runtime.sh" "Synology verify script exists"

section "Source and migration audit"
require_path "${PLATFORM_REPO}/services/ai-workspace-assistant/src/server.mjs" "AI Workspace Assistant source present"
require_path "${PLATFORM_REPO}/services/ai-workspace-assistant/src/templates/install-windows.ps1" "Worker installer template present"
require_path "${GATEWAY_REPO}/migrations/004_run_grants.sql" "Ops Gateway token-scoped run grants migration present"
require_file_contains "${GATEWAY_REPO}/docker-entrypoint.sh" "npm run migrate:dist" "Ops Gateway image applies migrations on startup"
require_file_contains "${PLATFORM_REPO}/infra/synology/backup-current.sh" "ai-workspace-assistant" "Backup includes AI Workspace Assistant source"
require_file_contains "${PLATFORM_REPO}/infra/synology/deploy-current.sh" "RSYNC_METADATA_ARGS" "Deploy sync avoids fragile NAS metadata by default"
require_file_contains "${PLATFORM_REPO}/infra/synology/apply-current-runtime.sh" "ai-workspace-ops-entitlement-env-ok" "Apply verifies Ops entitlement env"
require_file_contains "${PLATFORM_REPO}/infra/synology/verify-current-runtime.sh" "ai-workspace-ops-entitlement-env-ok" "Verify checks Ops entitlement env"

section "NAS env readiness"
if [[ -f "${NAS_PLATFORM_ENV}" ]]; then
  pass "NAS Platform env exists"
  require_env_value "${NAS_PLATFORM_ENV}" "AI_WORKSPACE_HUB_PUBLIC_URL" "wss://ai-hub.nodedc.ru/api/ai-workspace/hub" "NAS Platform worker-facing Hub URL"
  require_env_value "${NAS_PLATFORM_ENV}" "AI_WORKSPACE_HUB_INTERNAL_URL" "https://ai-hub.nodedc.ru" "NAS Platform internal Hub URL"
  require_env_value "${NAS_PLATFORM_ENV}" "AI_WORKSPACE_HUB_FALLBACK_URLS" "" "NAS Platform Hub fallback URLs disabled"
  require_env_value "${NAS_PLATFORM_ENV}" "AI_WORKSPACE_OPS_ENTITLEMENT_URL" "http://172.22.0.222:18190/api/internal/v1/ai-workspace/entitlements" "NAS Platform Ops entitlement URL"
  require_env_nonempty "${NAS_PLATFORM_ENV}" "AI_WORKSPACE_OPS_ENTITLEMENT_TOKEN" "NAS Platform Ops entitlement token configured"
  require_env_nonempty "${NAS_PLATFORM_ENV}" "AI_WORKSPACE_ASSISTANT_TOKEN" "NAS Platform Assistant token configured"
  require_env_nonempty "${NAS_PLATFORM_ENV}" "AI_WORKSPACE_HUB_TOKEN" "NAS Platform Hub token configured"
else
  fail "NAS Platform env missing: ${NAS_PLATFORM_ENV}"
fi

if [[ -f "${NAS_GATEWAY_ENV}" ]]; then
  pass "NAS Ops Gateway env exists"
  require_env_value "${NAS_GATEWAY_ENV}" "NODEDC_AGENT_GATEWAY_PUBLIC_URL" "https://ops-agents.nodedc.ru" "NAS Gateway worker-facing MCP URL"
  require_env_value "${NAS_GATEWAY_ENV}" "NODEDC_TASKER_INTERNAL_URL" "http://172.22.0.222:18090" "NAS Gateway downstream Tasker URL"
  require_env_value "${NAS_GATEWAY_ENV}" "NODEDC_AI_WORKSPACE_RUN_TOKEN_TTL_SECONDS" "43200" "NAS Gateway AI Workspace run token TTL"
  require_env_nonempty "${NAS_GATEWAY_ENV}" "NODEDC_AGENT_GATEWAY_INTERNAL_TOKEN" "NAS Gateway internal token configured"
  require_env_nonempty "${NAS_GATEWAY_ENV}" "NODEDC_INTERNAL_ACCESS_TOKEN" "NAS Gateway Tasker internal token configured"
  require_env_nonempty "${NAS_GATEWAY_ENV}" "POSTGRES_PASSWORD" "NAS Gateway Postgres password configured"
else
  fail "NAS Ops Gateway env missing: ${NAS_GATEWAY_ENV}"
fi

section "Controlled apply order"
cat <<EOF
1. Run local predeploy gate:
   cd ${PLATFORM_REPO}
   infra/scripts/check-ai-workspace-release-gates.sh

2. Create file backup from mounted NAS share:
   cd ${PLATFORM_REPO}
   NAS_ROOT=${NAS_ROOT} infra/synology/backup-current.sh

3. On Synology, run DB dumps from the backup folder:
   bash /volume1/docker/nodedc-platform/backups/<backup-id>/run-authentik-db-dump-on-synology.sh
   bash /volume1/docker/nodedc-platform/backups/<backup-id>/run-notification-db-dump-on-synology.sh
   bash /volume1/docker/nodedc-platform/backups/<backup-id>/run-ops-agents-db-dump-on-synology.sh
   # Tasker DB dump only if Tasker backend/schema changes are included:
   bash /volume1/docker/nodedc-platform/backups/<backup-id>/run-tasker-db-dump-on-synology.sh

4. Sync source to NAS mount:
   cd ${PLATFORM_REPO}
   NAS_ROOT=${NAS_ROOT} GATEWAY_REPO=${GATEWAY_REPO} infra/synology/deploy-current.sh

5. Apply Ops Gateway first on Synology:
   cd /volume1/docker/nodedc-platform/ops-agents
   sudo /usr/local/bin/docker compose --env-file .env -f docker-compose.synology.yml up -d --build --force-recreate
   curl -fsS http://172.22.0.222:18190/readyz

6. Apply Platform AI Workspace services on Synology:
   cd /volume1/docker/nodedc-platform/platform
   sudo bash apply-current-runtime.sh

7. Verify runtime:
   cd /volume1/docker/nodedc-platform/platform
   sudo bash verify-current-runtime.sh
EOF

section "Summary"
printf 'passed=%s failed=%s warnings=%s\n' "${passed}" "${failed}" "${warnings}"

if [[ "${failed}" -ne 0 ]]; then
  exit 1
fi
