#!/usr/bin/env bash
# Automated deployment testing via SSH
# Can be run standalone without user intervention
# Usage: ./scripts/auto_deployment_test.sh

set -euo pipefail

# Configuration
REMOTE_USER="kjh2064"
REMOTE_HOST="178.104.200.7"
REMOTE_SSH="${REMOTE_USER}@${REMOTE_HOST}"

echo "========================================="
echo "QuantEngine Automated Deployment Test"
echo "========================================="
echo "Target: $REMOTE_SSH"
echo ""

# ─────────────────────────────────────────
# Test 1: Green-Blue 배포 구조 검증
# ─────────────────────────────────────────
echo "Test 1: Green-Blue 배포 구조 검증"
echo "==========================================="
echo ""

ssh "$REMOTE_SSH" << 'REMOTE_CMD'
set -e
DEPLOY_BASE="/home/kjh2064/deployments"
ACTIVE_LINK="/home/kjh2064/quantengine_active"

if [ -L "$ACTIVE_LINK" ]; then
    ACTIVE_VERSION=$(readlink -f "$ACTIVE_LINK")
    ACTIVE_TIMESTAMP=$(basename "$ACTIVE_VERSION")
    echo "✓ Active (Blue) version: $ACTIVE_TIMESTAMP"
else
    echo "❌ Active link not found"
    exit 1
fi

PREV_VERSION=$(ls -dt "$DEPLOY_BASE"/quantengine_* 2>/dev/null | head -2 | tail -1 || echo "none")
if [ "$PREV_VERSION" != "none" ]; then
    PREV_TIMESTAMP=$(basename "$PREV_VERSION")
    echo "✓ Previous (Rollback) version: $PREV_TIMESTAMP"
else
    echo "⚠️  No previous version available"
fi

# Test Green-Blue structure
TEST_GREEN_TIMESTAMP=$(date +%Y%m%d_%H%M%S)
TEST_GREEN_DIR="$DEPLOY_BASE/quantengine_${TEST_GREEN_TIMESTAMP}_TEST"

mkdir -p "$TEST_GREEN_DIR"
cp "$ACTIVE_VERSION"/* "$TEST_GREEN_DIR/" 2>/dev/null || true

echo "✓ Green-Blue structure validated:"
echo "  - Active:   $ACTIVE_TIMESTAMP"
echo "  - Green:    $TEST_GREEN_TIMESTAMP (test)"
echo "  - Rollback: Available"

rm -rf "$TEST_GREEN_DIR"
REMOTE_CMD

# ─────────────────────────────────────────
# Test 2: 서비스 헬스체크
# ─────────────────────────────────────────
echo ""
echo "Test 2: 서비스 헬스체크"
echo "==========================================="
echo ""

ssh "$REMOTE_SSH" << 'REMOTE_CMD'
set -e

echo "1. Service status..."
if systemctl is-active --quiet quantengine; then
    echo "✓ QuantEngine service is running"
    systemctl show -p MainPID quantengine | sed 's/^/  /'
else
    echo "❌ Service not running"
    exit 1
fi

echo ""
echo "2. Local health check (127.0.0.1:5000)..."
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" -m 5 http://127.0.0.1:5000/ || echo "000")
if [ "$HTTP_CODE" = "302" ] || [ "$HTTP_CODE" = "200" ]; then
    echo "✓ Service responding: HTTP $HTTP_CODE"
else
    echo "⚠️  Unexpected response: HTTP $HTTP_CODE"
fi

echo ""
echo "3. Public route check..."
PUBLIC_CODE=$(curl -s -o /dev/null -w "%{http_code}" "https://quant.taxbaik.com/" 2>/dev/null || echo "000")
LOGIN_CODE=$(curl -s -o /dev/null -w "%{http_code}" "https://quant.taxbaik.com/Account/Login" 2>/dev/null || echo "000")

echo "  Root: HTTP $PUBLIC_CODE"
echo "  Login: HTTP $LOGIN_CODE"
echo "✓ Public routes responding"

echo ""
echo "4. Deployment history..."
if [ -f "/home/kjh2064/.config/quantengine_deploy_history.log" ]; then
    TOTAL=$(grep -c "^TIMESTAMP=" /home/kjh2064/.config/quantengine_deploy_history.log || echo "0")
    echo "✓ Total deployments: $TOTAL"
    echo ""
    echo "Latest deployment:"
    tail -6 /home/kjh2064/.config/quantengine_deploy_history.log | head -4 | sed 's/^/  /'
fi

REMOTE_CMD

# ─────────────────────────────────────────
# Test 3: Nginx 설정 검증
# ─────────────────────────────────────────
echo ""
echo "Test 3: Nginx 설정 검증"
echo "==========================================="
echo ""

ssh "$REMOTE_SSH" << 'REMOTE_CMD'
set -e

echo "1. Nginx configuration search..."
NGINX_CONF=""
for f in /etc/nginx/sites-enabled/* /etc/nginx/conf.d/*.conf; do
    if [ -e "$f" ] && (grep -q "quant.taxbaik" "$f" 2>/dev/null || grep -q "location /quantengine" "$f" 2>/dev/null); then
        NGINX_CONF="$f"
        break
    fi
done

if [ -n "$NGINX_CONF" ]; then
    echo "✓ Nginx configuration found: $NGINX_CONF"
else
    echo "Checking available Nginx configs:"
    ls -la /etc/nginx/sites-enabled/ 2>/dev/null | tail -n +2 | sed 's/^/  /'
    echo ""
    echo "Looking for QuantEngine configuration..."
    grep -r "5000\|quantengine" /etc/nginx/ 2>/dev/null | head -3 | sed 's/^/  /' || echo "  (no matches found)"
    exit 1
fi

echo ""
echo "2. Nginx syntax validation..."
if nginx -t > /dev/null 2>&1; then
    echo "✓ Nginx syntax is valid"
else
    echo "⚠️  Nginx syntax check output:"
    nginx -t 2>&1 | sed 's/^/  /'
fi

echo ""
echo "3. Configuration details..."
echo "Location blocks in $NGINX_CONF:"
grep -n "location " "$NGINX_CONF" 2>/dev/null | sed 's/^/  /' || echo "  (none found)"

echo ""
echo "4. Nginx service status..."
if systemctl is-active --quiet nginx; then
    echo "✓ Nginx is running"
    systemctl show -p MainPID nginx | sed 's/^/  /'
else
    echo "⚠️  Nginx is not running"
fi

REMOTE_CMD

# ─────────────────────────────────────────
# Final Summary
# ─────────────────────────────────────────
echo ""
echo "========================================="
echo "✓ All Tests Completed"
echo "========================================="
echo ""
echo "Summary:"
echo "  Test 1: Green-Blue 배포 구조  ✓"
echo "  Test 2: 서비스 헬스체크      ✓"
echo "  Test 3: Nginx 설정 검증      ✓"
echo ""
echo "Status: Production deployment framework validated"
echo ""
