#!/usr/bin/env bash
# Verify docker-compose.yml (production): syntax and required services
# Usage: ./scripts/verify-prod-compose.sh
# Run from project root. Requires: bash, optional docker compose / docker-compose
# Production: ensure .env exists with POSTGRES_PASSWORD, JWT_SECRET_KEY, ADMIN_* (see .env.example).

set -e
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"
COMPOSE_FILE="docker-compose.yml"

echo "Checking $COMPOSE_FILE exists..."
test -f "$COMPOSE_FILE" || { echo "Missing $COMPOSE_FILE"; exit 1; }

echo "Validating YAML syntax and required services (Python)..."
python3 - "$COMPOSE_FILE" <<'PY'
import sys
try:
    import yaml
except ImportError:
    print("PyYAML not installed, skipping YAML check")
    sys.exit(0)

path = sys.argv[1]
with open(path) as f:
    data = yaml.safe_load(f)

if not data or "services" not in data:
    print("YAML error: no 'services' key")
    sys.exit(1)

services = data["services"]
required = {"postgres", "redis", "backend", "frontend"}
missing = required - set(services)
if missing:
    print("YAML error: missing required services:", ", ".join(sorted(missing)))
    sys.exit(1)
print("YAML OK, required services present (postgres, redis, backend, frontend)")
PY

if command -v docker-compose &>/dev/null; then
    echo "Running docker-compose config..."
    docker-compose -f "$COMPOSE_FILE" config >/dev/null && echo "docker compose config OK"
elif docker compose version &>/dev/null 2>&1; then
    echo "Running docker compose config..."
    docker compose -f "$COMPOSE_FILE" config >/dev/null && echo "docker compose config OK"
else
    echo "Docker Compose not found; skip config validation. Run manually: docker compose -f $COMPOSE_FILE up -d"
fi

echo "Done. To start prod stack: docker compose up -d (ensure .env has POSTGRES_PASSWORD, JWT_SECRET_KEY, ADMIN_*)"
