#!/bin/bash
# ==========================================
# Deploy update — быстрый деплой фиксов
# Usage: bash other/deploy_update.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

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
SERVER="angel@81.177.141.34"
ARCHIVE="$SCRIPT_DIR/aegisone-update.tar.gz"
BOT="/opt/projects/aegisone-py/max_bot"
PY="/opt/projects/aegisone-py"

echo "=========================================="
echo "  AegisOne — Deploy Update"
echo "=========================================="

# ==========================================
# Gate: run tests before deploy
# ==========================================
if [ "$SKIP_TESTS" = false ]; then
    echo ""
    echo "[CHECK] Running tests..."
    cd "$REPO_ROOT/py_service"
    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
else
    echo "  ⚠️  Tests skipped (--skip-tests flag)"
fi

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

echo ""
echo "[1/5] Uploading archive..."
scp "$ARCHIVE" "$SERVER:/tmp/aegisone-update.tar.gz"

echo ""
echo "[2/5] Applying update on server..."
ssh "$SERVER" << 'SSHEOF'
    set -e
    cd /tmp
    rm -rf update
    mkdir update && tar xzf aegisone-update.tar.gz -C update
    PY="/opt/projects/aegisone-py"

    # SQL migration (если есть)
    MIG=$(ls update/py_service/sql/v*.sql 2>/dev/null | head -1)
    if [ -n "$MIG" ]; then
        PG=$(docker ps --filter "name=aegisone-postgres" --format "{{.ID}}" | head -1)
        if [ -n "$PG" ]; then
            docker cp "$MIG" "$PG:/tmp/mig.sql"
            docker exec "$PG" psql -U aegisone -d aegisone -f /tmp/mig.sql 2>&1 | grep -v "^ALTER\|^CREATE\|^INSERT\|^ON CONFLICT" || true
            echo "  ✅ Migration applied"
        fi
    fi

    # Copy all py_service files
    rsync -a --delete update/py_service/ "$PY/"
    echo "  ✅ py_service files copied"

    # Copy max_bot files (если есть)
    if [ -d "update/max_bot" ]; then
        rsync -a --delete update/max_bot/ "$PY/max_bot/"
        echo "  ✅ max_bot files copied"
    fi

    rm -rf /tmp/update
SSHEOF

echo ""
echo "[3/5] Rebuilding max_bot container..."
ssh "$SERVER" "cd $BOT && docker compose up -d --build 2>&1 | tail -5"

echo ""
echo "[4/5] Rebuilding py_service container..."
ssh "$SERVER" "cd $PY && docker compose up -d --build 2>&1 | tail -5"

echo ""
echo "[5/5] Health check..."
sleep 5
ssh "$SERVER" '
    echo -n "  max_bot:    "
    curl -s -o /dev/null -w "%{http_code}" http://localhost:8002/health || echo "FAIL"
    echo -n "  py_service:  "
    curl -s -o /dev/null -w "%{http_code}" http://localhost:8000/health || echo "FAIL"
'

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

echo ""
echo "=========================================="
echo "  ✅ Update complete: v$VERSION"
echo "  Bot:   https://max.aegisone.ru"
echo "  Portal: https://service.aegisone.ru"
echo "=========================================="
