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

HOST="${1:-root@76.13.31.179}"
APP_DIR="${APP_DIR:-/opt/skg-marketing-studio}"

ssh "$HOST" "cd '$APP_DIR' && \
  docker ps --filter name=skg-marketing --format '{{.Names}} {{.Status}}' && \
  docker exec skg-marketing-web sh -lc '
    set -e
    echo web:no_local_api_refs
    if grep -Rao \"http://localhost:4291\\|http://127.0.0.1:4291\\|localhost:4290\\|127.0.0.1:4290\" /usr/share/nginx/html/_next/static 2>/dev/null | head -1 | grep -q .; then
      echo \"ERROR: local API/dev URL leaked into web static bundle\" >&2
      exit 1
    fi
    for p in / /login/ /_next/does-not-exist.js /api/health; do
      code=\$(curl -sS -o /tmp/skg-smoke.out -w \"%{http_code}\" \"http://127.0.0.1\$p\")
      case \"\$p:\$code\" in
        /:302|/login/:200|/_next/does-not-exist.js:404|/api/health:401) echo \"web:\$p \$code\" ;;
        *) echo \"ERROR: unexpected web route status \$p \$code\" >&2; head -c 200 /tmp/skg-smoke.out >&2; exit 1 ;;
      esac
    done
  ' && \
  docker exec skg-marketing-api sh -lc '
    set -e
    test ! -f /app/.env || { echo \"ERROR: /app/.env leaked into API image\" >&2; exit 1; }
    python -c \"import main; assert main.YTDLP_COOKIES_FROM_BROWSER == \\\"\\\", main.YTDLP_COOKIES_FROM_BROWSER; print(\\\"api:ytdlp_cookie_args\\\", main.ytdlp_cookie_args())\"
    curl -sS http://127.0.0.1:4291/health | python -c \"import json,sys; d=json.load(sys.stdin); assert d[\\\"ok\\\"] is True; assert d[\\\"auth_configured\\\"] is True; print(\\\"api:health ok\\\")\"
  '"
