#!/usr/bin/env bash
# Deploy script for AegisOne Service Portal
# Usage: ./deploy.sh [--skip-tests] [patch|minor|major]
set -e

SKIP_TESTS=false
BUMP="patch"
for arg in "$@"; do
    case "$arg" in
        --skip-tests) SKIP_TESTS=true ;;
        patch|minor|major) BUMP="$arg" ;;
    esac
done

DIR="$(cd "$(dirname "$0")" && pwd)"

# Gate: run tests before deploy
if [ "$SKIP_TESTS" = false ]; then
    echo ""
    echo "[CHECK] Running tests..."
    cd "$DIR"
    if curl -sf http://localhost:8000/health > /dev/null 2>&1; then
        if ! pytest -v --tb=short -x; then
            echo ""
            echo "❌ Tests failed. Deploy aborted."
            echo "   Fix errors or use --skip-tests to force deploy."
            exit 1
        fi
        echo "  ✅ Tests passed"
    else
        echo "  ⚠️  Server not reachable at localhost:8000"
        echo "     Start the service first, or use --skip-tests"
        exit 1
    fi
fi

echo "=== AegisOne Service Portal Deploy ==="
echo ""

# Bump version
cd "$DIR"
python scripts/bump_version.py "$BUMP" '{"features":["Обновление сервисного портала"],"fixes":["Исправления и улучшения"]}'
VERSION=$(cat version.txt)
echo "Version: $VERSION"

# Create archive
cd ..
ARCHIVE="other/aegisone-py-deploy.tar.gz"
tar czf "$ARCHIVE" \
  py_service/ --exclude='py_service/__pycache__' --exclude='py_service/.venv' --exclude='py_service/.git' --exclude='py_service/app/__pycache__' --exclude='py_service/app/**/__pycache__' \
  max_bot/ --exclude='max_bot/__pycache__' --exclude='max_bot/.venv'
echo "Archive created: $ARCHIVE"

# Upload
scp "$ARCHIVE" angel@81.177.141.34:/opt/projects/
echo "Uploaded to server"

# Deploy on server
ssh angel@81.177.141.34 << 'SSHEOF'
    set -e
    cd /opt/projects
    rm -rf aegisone-py-backup 2>/dev/null || true
    mv aegisone-py aegisone-py-backup 2>/dev/null || true
    mkdir -p aegisone-py
    tar xzf aegisone-py-deploy.tar.gz -C aegisone-py --strip-components=1
    cd aegisone-py
    docker compose down
    docker compose build --no-cache --network host
    docker compose up -d
    echo "Service restarted"

    # Deploy max_bot
    echo ""
    echo "--- Deploying max_bot ---"
    if [ -d "/opt/projects/max_bot" ]; then
        bash max_bot/max_bot_deploy.sh
    else
        echo "⚠️  max_bot directory not found — skipping"
    fi
SSHEOF

# Commit changelog
git add py_service/version.txt py_service/CHANGELOG.md
git diff --cached --quiet || git commit -m "v$VERSION: changelog [skip ci]"

echo "=== Deploy complete: v$VERSION ==="
