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

usage() {
  cat <<'USAGE'
Usage: scripts/kb-control-plane-cutover.sh [dry-run|verify|apply|rollback-plan]

Batch 4 KB control-plane cutover helper.
- dry-run: print checks and run read-only evidence collection.
- verify: enforce read-only grep/schema evidence; exits non-zero on violations.
- apply: idempotent post-cleanup verification. No data mutation is performed.
- rollback-plan: print operational rollback steps.

Optional database verification:
  AGENTTEAM_CORE_MYSQL_DATABASE  If set, verify checks this AgentTeam core schema for the removed legacy table.
  AGENTTEAM_CORE_MYSQL_HOST      MySQL host for the optional check (default: 127.0.0.1).
  AGENTTEAM_CORE_MYSQL_PORT      MySQL port for the optional check (default: 3306).
  AGENTTEAM_CORE_MYSQL_USER      MySQL user for the optional check (default: root).
  AGENTTEAM_CORE_MYSQL_PASSWORD  MySQL password for the optional check (optional; passed via MYSQL_PWD).

The optional database check intentionally uses explicit mysql CLI connection fields,
not the Go-style storage DSN such as root@tcp(host:port)/database.
USAGE
}

mode="${1:-dry-run}"
case "$mode" in
  dry-run|verify|apply|rollback-plan|-h|--help|help) ;;
  *) usage >&2; exit 2 ;;
esac
if [[ "$mode" == "-h" || "$mode" == "--help" || "$mode" == "help" ]]; then
  usage
  exit 0
fi

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

run_rg_expect_empty() {
  local description="$1"
  shift
  echo "==> $description"
  if rg "$@"; then
    echo "violation: $description" >&2
    return 1
  fi
  echo "ok: no matches"
}

run_rg_expect_matches() {
  local description="$1"
  shift
  echo "==> $description"
  rg "$@"
}

verify_database_if_configured() {
  if [[ -z "${AGENTTEAM_CORE_MYSQL_DATABASE:-}" ]]; then
    echo "==> database table check"
    echo "skipped: AGENTTEAM_CORE_MYSQL_DATABASE is not set"
    return 0
  fi

  local host="${AGENTTEAM_CORE_MYSQL_HOST:-127.0.0.1}"
  local port="${AGENTTEAM_CORE_MYSQL_PORT:-3306}"
  local user="${AGENTTEAM_CORE_MYSQL_USER:-root}"
  local database="$AGENTTEAM_CORE_MYSQL_DATABASE"
  local count

  echo "==> database table check"
  count="$(MYSQL_PWD="${AGENTTEAM_CORE_MYSQL_PASSWORD:-}" mysql \
    --protocol=TCP \
    --host="$host" \
    --port="$port" \
    --user="$user" \
    --database="$database" \
    --batch \
    --skip-column-names \
    --execute "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'channel_knowledge_base_shares';")"
  count="$(printf '%s' "$count" | tr -d '[:space:]')"
  case "$count" in
    0)
      echo "ok: channel_knowledge_base_shares is absent from ${database}"
      ;;
    ''|*[!0-9]*)
      echo "violation: unexpected database table check result: ${count:-<empty>}" >&2
      return 1
      ;;
    *)
      echo "violation: legacy channel_knowledge_base_shares table still exists in ${database}" >&2
      return 1
      ;;
  esac
}

print_plan() {
  cat <<'PLAN'
Batch 4 cutover plan:
1. Keep MeshX KB store/service/API as source of truth.
2. Keep AgentTeam gateway stable v1 KB routes.
3. Remove old channel KB compatibility fallback routes from AgentTeam after Web cutover.
4. Verify Web has no legacy channel KB API calls and no direct MeshX endpoint/token usage.
5. Verify AgentTeam has no KB control-plane store/API ownership or double-write logic.
6. Treat MeshX empty results as source-of-truth empty results; do not repopulate from AgentTeam.
PLAN
}

rollback_plan() {
  cat <<'ROLLBACK'
Rollback plan:
1. Revert the Batch 4 cleanup PR if compatibility routes must be temporarily restored.
2. Do not recreate AgentTeam KB control-plane writes or dual writes; MeshX remains source of truth.
3. If persistent data rollback is required, restore from a database backup/snapshot taken before rollout.
4. Re-run this script in verify mode before retrying cutover.
ROLLBACK
}

run_checks() {
  run_rg_expect_matches "stable gateway KB routes are present" '/api/v1/(channels/.+/kb|kb)' web/src/agentteam/api internal/forwarder internal/api
  run_rg_expect_empty "Web must not call legacy channel KB API" '/api/channels/.+knowledge-bases' web/src/agentteam/api web/src/agentteam/workspace web/src/agentteam/pages/WorkspaceShell.tsx
  run_rg_expect_empty "Web must not direct-connect to MeshX or manage MeshX tokens" '/api/meshx|MeshX.*token|token.*MeshX|https?://.*meshx' web/src/agentteam/api web/src/agentteam/workspace
  run_rg_expect_empty "AgentTeam must not own KB control-plane storage/API or legacy compatibility route" 'channel_knowledge|KnowledgeBaseShare|knowledge_base_shares|/api/channels/.+knowledge-bases' internal/api internal/store internal/forwarder web/src/agentteam/api
  run_rg_expect_empty "AgentTeam/Web must not use /api/meshx" '/api/meshx' internal web/src/agentteam
  verify_database_if_configured
}

case "$mode" in
  dry-run)
    print_plan
    run_checks
    ;;
  verify)
    run_checks
    ;;
  apply)
    echo "apply is idempotent: no data mutation is required after code cleanup. Running verification."
    run_checks
    ;;
  rollback-plan)
    rollback_plan
    ;;
esac
