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

ROOT=$(git rev-parse --show-toplevel 2>/dev/null || pwd)
cd "$ROOT"

SPEC="specs/deployment/workspace-gateway.md"
README="specs/deployment/README.md"

fail() {
  printf "FAIL: %s\n" "$1" >&2
  exit 1
}

[[ -f "$SPEC" ]] || fail "$SPEC must exist"
[[ -f "cmd/agentteam-gateway-server/main.go" ]] || fail "cmd/agentteam-gateway-server/main.go must exist"
[[ -f "cmd/agentteam-gateway-server/main_test.go" ]] || fail "cmd/agentteam-gateway-server/main_test.go must exist"
[[ -f "internal/gateway/gateway.go" ]] || fail "internal/gateway/gateway.go must exist"
[[ -f "internal/gateway/gateway_test.go" ]] || fail "internal/gateway/gateway_test.go must exist"
grep -Fq "Canonical path: \`specs/deployment/workspace-gateway.md\`" "$SPEC" || fail "$SPEC must declare canonical path"
grep -Fq "[AgentTeam Workspace Gateway](./workspace-gateway.md)" "$README" || fail "$README must link workspace gateway spec"

declare -a required=(
  "agentteam-central-server"
  "agentteam-workspace-server"
  "agentteam-gateway-server"
  "cmd/agentteam-gateway-server"
  "profile=all"
  "X-AgentTeam-Route-Workspace-Id"
  "must not read \`X-Workspace-Id\` as a long-term compatibility routing input"
  "workspace_placements"
  "workspace-placement-verify --workspace-group-id workspace-default"
  "workspace-placement-topology-verify"
  "missing placement must fail closed 4xx"
  "must not silently fallback missing placements to \`workspace-default\`"
  "/api/v1/workspaces/:workspaceId/events/stream"
  "no realtime-specific ALB rule"
  "config.workspace_id"
  "AGENTTEAM_ADMIN_BASE_URL"
  "AGENTTEAM_ADMIN_SERVICE_TOKEN"
  "AGENTTEAM_GATEWAY_CENTRAL_UPSTREAM_URL"
  "AGENTTEAM_GATEWAY_WORKSPACE_UPSTREAMS"
  "AGENTTEAM_DATABASE_DSN"
  "current production observed peak usage multiplied by 1.5"
  "Start \`agentteam-central-server\` as \`1/1\`"
  "Render validation must fail if any public Ingress contains workspace-group-specific ALB conditions"
)

declare -a code_required=(
  "package gateway"
  "api.HeaderRouteWorkspaceID"
  "HeaderWorkspaceID"
  "PlacementStateActive"
  "workspaceV1IMRoute"
  "AGENTTEAM_GATEWAY_CENTRAL_UPSTREAM_URL"
  "AGENTTEAM_GATEWAY_WORKSPACE_UPSTREAMS"
)

for pattern in "${required[@]}"; do
  grep -Fq "$pattern" "$SPEC" || fail "$SPEC missing required text: $pattern"
done

for pattern in "${code_required[@]}"; do
  grep -R -Fq "$pattern" internal/gateway cmd/agentteam-gateway-server || fail "gateway implementation missing required text: $pattern"
done

if grep -Fq "Raising the ALB quota as the primary fix" "$SPEC" && \
   grep -Fq "Continuing to duplicate ALB path/header rules per workspace group" "$SPEC"; then
  :
else
  fail "$SPEC must explicitly reject ALB quota and per-group ALB rule duplication as primary fixes"
fi

if grep -Fq "agentteam-workspace-gateway" "$SPEC"; then
  fail "$SPEC must use agentteam-gateway-server naming instead of agentteam-workspace-gateway"
fi

printf "Workspace gateway spec guardrail passed.\n"
