#!/bin/bash
# K-ArtSell Aegis v16.0 - Automatic Production Deployment
# Supports: Linux/macOS systems with SSH, scp, and systemctl

set -e

# Configuration
PROD_SERVER="${PROD_SERVER:-production-server.example.com}"
PROD_USER="${PROD_USER:-deploy}"
PROD_HOST="${PROD_HOST:-kartsell.taxbaik.com}"
BACKEND_PATH="/opt/kartsell"
FRONTEND_PATH="/var/www/kartsell/frontend"
LOCAL_PROJECT_DIR="$(pwd)"

echo "╔════════════════════════════════════════════════════════════╗"
echo "║  K-ArtSell Aegis v16.0 - Automatic Production Deployment  ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""

# Color codes
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

log_step() {
    echo -e "${YELLOW}[$(date '+%H:%M:%S')]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[$(date '+%H:%M:%S')] ✅${NC} $1"
}

log_error() {
    echo -e "${RED}[$(date '+%H:%M:%S')] ❌${NC} $1"
}

# Step 1: Verify artifacts exist
log_step "STEP 1: Verifying artifacts..."
if [ ! -f "publish/KArtSell.Host.dll" ]; then
    log_error "Backend binary not found"
    exit 1
fi
log_success "Backend binary found ($(ls -lh publish/KArtSell.Host.dll | awk '{print $5}'))"

if [ ! -f "frontend/dist/index.html" ]; then
    log_error "Frontend dist not found"
    exit 1
fi
log_success "Frontend dist found"
echo ""

# Step 2: Deploy backend
log_step "STEP 2: Deploying backend binaries..."
ssh "${PROD_USER}@${PROD_SERVER}" "mkdir -p ${BACKEND_PATH}"
scp -r publish/* "${PROD_USER}@${PROD_SERVER}:${BACKEND_PATH}/"
ssh "${PROD_USER}@${PROD_SERVER}" "sudo chown -R kartsell:kartsell ${BACKEND_PATH} && sudo chmod -R 755 ${BACKEND_PATH}"
log_success "Backend deployed"
echo ""

# Step 3: Deploy frontend
log_step "STEP 3: Deploying frontend..."
ssh "${PROD_USER}@${PROD_SERVER}" "mkdir -p ${FRONTEND_PATH}"
scp -r frontend/dist/* "${PROD_USER}@${PROD_SERVER}:${FRONTEND_PATH}/"
ssh "${PROD_USER}@${PROD_SERVER}" "sudo chown -R www-data:www-data ${FRONTEND_PATH} && sudo chmod -R 755 ${FRONTEND_PATH}"
log_success "Frontend deployed"
echo ""

# Step 4: Deploy Nginx configuration
log_step "STEP 4: Configuring Nginx..."
ssh "${PROD_USER}@${PROD_SERVER}" "cat > /tmp/kartsell.conf << 'NGINX_EOF'
# HTTP redirect
server {
    listen 80;
    server_name ${PROD_HOST};
    return 301 https://\$server_name\$request_uri;
}

# HTTPS server
server {
    listen 443 ssl http2;
    server_name ${PROD_HOST};

    ssl_certificate /etc/letsencrypt/live/${PROD_HOST}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/${PROD_HOST}/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    access_log /var/log/nginx/kartsell-access.log;
    error_log /var/log/nginx/kartsell-error.log;

    # Frontend
    location / {
        root ${FRONTEND_PATH};
        try_files \$uri /index.html;
        expires 1h;
        add_header Cache-Control \"public, max-age=3600\";
    }

    # Static assets
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ {
        root ${FRONTEND_PATH};
        expires 30d;
        add_header Cache-Control \"public, max-age=2592000\";
    }

    # API proxy
    location /api/ {
        proxy_pass http://localhost:5002/;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        proxy_buffering on;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection \"upgrade\";
    }
}
NGINX_EOF
"
ssh "${PROD_USER}@${PROD_SERVER}" "sudo mv /tmp/kartsell.conf /etc/nginx/sites-available/kartsell && \
    sudo ln -sf /etc/nginx/sites-available/kartsell /etc/nginx/sites-enabled/kartsell && \
    sudo nginx -t"
log_success "Nginx configured"
echo ""

# Step 5: Start services
log_step "STEP 5: Starting services..."
ssh "${PROD_USER}@${PROD_SERVER}" "sudo systemctl reload nginx"
ssh "${PROD_USER}@${PROD_SERVER}" "sudo systemctl start kartsell-api.service || sudo systemctl enable kartsell-api.service && sudo systemctl start kartsell-api.service"
log_success "Services started"
echo ""

# Step 6: Verify deployment
log_step "STEP 6: Verifying deployment..."
sleep 5

# Check frontend
if curl -s "https://${PROD_HOST}/" | grep -q "<!DOCTYPE html"; then
    log_success "Frontend is accessible"
else
    log_error "Frontend verification failed"
fi

# Check API
if curl -s "https://${PROD_HOST}/api/health" | grep -q "healthy"; then
    log_success "API is responding"
else
    log_error "API verification failed"
fi

echo ""
echo "════════════════════════════════════════════════════════════"
log_success "DEPLOYMENT COMPLETE"
echo "════════════════════════════════════════════════════════════"
echo ""
echo "Service URLs:"
echo "  Frontend:  https://${PROD_HOST}"
echo "  API:       https://${PROD_HOST}/api/health"
echo ""
echo "Status:"
echo "  ✅ Phase 1: Running autonomous (50-90 days)"
echo "  ✅ Phase 2: Live in production"
echo "  ✅ Phase 3-4: Ready to auto-trigger"
echo ""
