#!/bin/bash
# Deploy homologação Agentic Ops — VM122 staging (portas 8180/8192)
# NÃO altera produção em :8080/:8091
set -euo pipefail

STAGING_DIR="/opt/ligbox-ops-platform-staging"
REPO="/opt/ligbox-spec-hub/repos/ligbox-ops-platform"
BRANCH="${1:-029-agentic-ops-runbooks}"

echo "==> Staging Agentic Ops branch=$BRANCH"

mkdir -p "$STAGING_DIR" /var/lib/ligbox-ops-platform-staging

# Sync código (symlinks api/frontend/worker do repo)
rsync -a --delete \
  --exclude '.git' --exclude 'chat-bruto' --exclude 'node_modules' \
  "$REPO/projects/ops-desk/" "$STAGING_DIR/"

rsync -a "$REPO/specs/" "$STAGING_DIR/specs/"

cd "$STAGING_DIR"

if [[ ! -f .env ]]; then
  if [[ -f /opt/ligbox-ops-platform/.env ]]; then
    cp /opt/ligbox-ops-platform/.env .env
    sed -i 's|SQLITE_PATH=.*|SQLITE_PATH=/data/ops-staging.db|' .env
    echo "AGENTIC_LLM_ENABLED=true" >> .env
    echo "AGENTIC_SPECS_ROOT=/opt/ligbox-ops-platform/specs" >> .env
  else
    echo "ERRO: .env não encontrado — copie manualmente" >&2
    exit 1
  fi
fi

docker compose -f docker-compose.agentic-staging.yml up -d --build

sleep 8
echo "==> Health staging"
curl -sf "http://10.10.10.122:8180/api/health" | head -c 200; echo
curl -sf "http://10.10.10.122:8180/api/v1/agents/health" | head -c 300; echo

TOKEN=$(grep OPS_INTERNAL_TOKEN .env | cut -d= -f2)
curl -sf -X POST "http://10.10.10.122:8180/api/v1/agents/internal/tick" \
  -H "X-Ops-Internal-Token: $TOKEN" | head -c 400; echo

echo "==> Staging UI: http://10.10.10.122:8192"
echo "==> Staging API: http://10.10.10.122:8180"
