#!/usr/bin/env bash
# Deploy COMPLETO Desk produção — API + frontend + catálogo RBAC + smoke GREEN
#
# Regra: nunca docker cp parcial. UI + API no mesmo pacote.
# VM112 wizard: usar deploy-wizard-vm112-smoke.sh separadamente se alterar carbonio.
#
# Uso: ./deploy-desk-full.sh [root@10.10.10.122]
# Env: DESK_SSH_PASS (default 805353), SKIP_SMOKE=1 para pular smoke

set -euo pipefail

HOST="${1:-root@10.10.10.122}"
PASS="${DESK_SSH_PASS:-805353}"
API_C="ligbox-ops-platform_api_1"
FE_C="ligbox-ops-platform_frontend_1"
REPO="$(cd "$(dirname "$0")/../.." && pwd)"
API="${REPO}/projects/ops-desk/api/app"
FE="${REPO}/projects/ops-desk/frontend"
ASSETS="${FE}/assets"
CATALOG="${REPO}/specs/039-ligbox-ops-authorization-catalog/contracts/action-catalog.yaml"
REMOTE="/tmp/desk-full-deploy"
MIN_AGENTIC_JS_LINES=1200
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "==> Deploy Desk FULL (API + UI) → ${HOST}"
echo "==> Repo: ${REPO}"

sshpass -p "${PASS}" ssh -o StrictHostKeyChecking=no "${HOST}" "mkdir -p ${REMOTE}/api ${REMOTE}/frontend/assets ${REMOTE}/catalog"

# --- API ---
API_FILES=(
  main.py governance_routes.py desk_governance_store.py action_catalog.py
  ops_inbox_routes.py ops_inbox_store.py email_relay.py email_relay_routes.py
  auth_routes.py permissions.py rbac_matrix.py rbac_routes.py registration_routes.py
  stack_health.py infra_stack_routes.py vm112_domains.py vm112_domains_routes.py
  billing_routes.py billing_store.py client_activation.py activation_mapper.py
)

for f in "${API_FILES[@]}"; do
  [[ -f "${API}/${f}" ]] || { echo "ERRO: falta ${API}/${f}" >&2; exit 1; }
done

sshpass -p "${PASS}" scp -o StrictHostKeyChecking=no \
  "${API_FILES[@]/#/${API}/}" \
  "${HOST}:${REMOTE}/api/"

[[ -f "$CATALOG" ]] && sshpass -p "${PASS}" scp -o StrictHostKeyChecking=no \
  "$CATALOG" "${HOST}:${REMOTE}/catalog/action-catalog.yaml"

# --- Frontend (pacote atómico Spec 039/040/030) ---
FE_FILES=(
  index.html
  topnav.js desk-modern.css styles.css
  app.js app.staging.js
  modules.js auth.js servicos.js billing-ui.js desk-live-stub.js dns-viewer.js
  tickets-sla.js tickets-workspace.js tickets-workspace.css tickets-detail-panel.js
  agentic-ops.js agentic-ops.css
  access-matrix.js access-matrix.css
  access-control-hub.js access-control-panel.js access-control-support.css
  ligbox-ds.css user-wizard.js user-management-panel.js
  operational-feed.js executive-map-panel.js infra-stack-meta.js
)

for f in "${FE_FILES[@]}"; do
  if [[ "$f" == "index.html" ]]; then
    sshpass -p "${PASS}" scp -o StrictHostKeyChecking=no "${FE}/${f}" "${HOST}:${REMOTE}/frontend/"
  else
    sshpass -p "${PASS}" scp -o StrictHostKeyChecking=no "${ASSETS}/${f}" "${HOST}:${REMOTE}/frontend/assets/"
  fi
done

sshpass -p "${PASS}" ssh -o StrictHostKeyChecking=no "${HOST}" bash -s <<EOF
set -e
for f in ${REMOTE}/api/*.py; do
  docker cp "\$f" ${API_C}:/app/app/\$(basename "\$f")
done
if [[ -f ${REMOTE}/catalog/action-catalog.yaml ]]; then
  docker exec ${API_C} mkdir -p /app/app/data /opt/ligbox-ops-platform/specs/039-ligbox-ops-authorization-catalog/contracts
  docker cp ${REMOTE}/catalog/action-catalog.yaml ${API_C}:/app/app/data/action-catalog.yaml
  docker cp ${REMOTE}/catalog/action-catalog.yaml ${API_C}:/opt/ligbox-ops-platform/specs/039-ligbox-ops-authorization-catalog/contracts/action-catalog.yaml
fi
docker restart ${API_C}
sleep 6
curl -sf http://127.0.0.1:8080/api/health | head -c 80; echo

docker cp ${REMOTE}/frontend/index.html ${FE_C}:/usr/share/nginx/html/index.html
for f in ${REMOTE}/frontend/assets/*; do
  docker cp "\$f" ${FE_C}:/usr/share/nginx/html/assets/\$(basename "\$f")
done

AGENTIC_LINES=\$(docker exec ${FE_C} wc -l /usr/share/nginx/html/assets/agentic-ops.js | awk '{print \$1}')
if [[ "\${AGENTIC_LINES}" -lt ${MIN_AGENTIC_JS_LINES} ]]; then
  echo "ERRO: agentic-ops.js \${AGENTIC_LINES} linhas" >&2
  exit 1
fi
docker exec ${FE_C} grep -q "Squad Command" /usr/share/nginx/html/assets/agentic-ops.js
docker exec ${FE_C} test -f /usr/share/nginx/html/assets/user-wizard.js
docker exec ${FE_C} test -f /usr/share/nginx/html/assets/operational-feed.js
docker exec ${API_C} python3 -c "from app.governance_routes import router; assert router.prefix == '/api/v1/governance'"
echo "=== Deploy containers OK ==="
EOF

if [[ "${SKIP_SMOKE:-}" != "1" ]]; then
  echo ""
  echo "==> Smoke tests"
  DESK_SSH_PASS="${PASS}" "${SCRIPT_DIR}/smoke-desk.sh" "https://desk.ligbox.com.br"
fi

echo ""
echo "Deploy completo: https://desk.ligbox.com.br/?desk=1"
echo "Commit deployado: $(cd "${REPO}" && git rev-parse --short HEAD 2>/dev/null || echo unknown)"
