#!/bin/bash
#
# POUNCE DEPLOYMENT SCRIPT
# ========================
# Run this locally to deploy to production
#
# Usage:
#   ./scripts/deploy.sh           # Deploy both frontend and backend
#   ./scripts/deploy.sh backend   # Deploy backend only
#   ./scripts/deploy.sh frontend  # Deploy frontend only
#

set -e

# Configuration
SERVER="185.142.213.170"
SSH_KEY="${SSH_KEY:-$HOME/.ssh/pounce_server}"
SSH_USER="administrator"
REMOTE_TMP="/tmp/pounce"
REMOTE_REPO="/home/administrator/pounce"
REMOTE_ENV_DIR="/data/pounce/env"

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

log() { echo -e "${GREEN}[DEPLOY]${NC} $1"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }

# Check SSH key
if [ ! -f "$SSH_KEY" ]; then
    error "SSH key not found: $SSH_KEY"
fi

if [ -z "${DEPLOY_SUDO_PASSWORD:-}" ]; then
    error "DEPLOY_SUDO_PASSWORD is required (export it locally, do not commit it)."
fi

# What to deploy
DEPLOY_BACKEND=true
DEPLOY_FRONTEND=true

if [ "$1" = "backend" ]; then
    DEPLOY_FRONTEND=false
    log "Deploying backend only"
elif [ "$1" = "frontend" ]; then
    DEPLOY_BACKEND=false
    log "Deploying frontend only"
else
    log "Deploying both frontend and backend"
fi

# Sync and build backend
if [ "$DEPLOY_BACKEND" = true ]; then
    log "Syncing backend code..."
    rsync -avz --delete \
        -e "ssh -i $SSH_KEY -o StrictHostKeyChecking=no" \
        --exclude '__pycache__' \
        --exclude '*.pyc' \
        --exclude '.git' \
        --exclude 'venv' \
        backend/ \
        ${SSH_USER}@${SERVER}:${REMOTE_REPO}/backend/

    log "Building backend image..."
    ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no ${SSH_USER}@${SERVER} \
        "printf '%s\n' \"${DEPLOY_SUDO_PASSWORD}\" | sudo -S docker build -t pounce-backend:latest ${REMOTE_REPO}/backend/" || error "Backend build failed"

    log "Deploying backend container..."
    ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no ${SSH_USER}@${SERVER} << BACKEND_DEPLOY
printf '%s\n' "${DEPLOY_SUDO_PASSWORD}" | sudo -S bash -c '
set -e

mkdir -p "${REMOTE_ENV_DIR}" /data/pounce/zones
chmod -R 755 /data/pounce || true

# Backend env must exist on server (created by CI or manually)
if [ ! -f "${REMOTE_ENV_DIR}/backend.env" ]; then
  echo "Missing ${REMOTE_ENV_DIR}/backend.env"
  exit 1
fi

docker stop pounce-backend 2>/dev/null || true
docker rm pounce-backend 2>/dev/null || true

docker run -d \
  --name pounce-backend \
  --network coolify \
  --shm-size=8g \
  --env-file "${REMOTE_ENV_DIR}/backend.env" \
  -v /data/pounce/zones:/data \
  --label "traefik.enable=true" \
  --label "traefik.http.routers.pounce-backend.rule=Host(\`api.pounce.ch\`)" \
  --label "traefik.http.routers.pounce-backend.entrypoints=https" \
  --label "traefik.http.routers.pounce-backend.tls=true" \
  --label "traefik.http.routers.pounce-backend.tls.certresolver=letsencrypt" \
  --label "traefik.http.services.pounce-backend.loadbalancer.server.port=8000" \
  --health-cmd "curl -f http://localhost:8000/health || exit 1" \
  --health-interval 30s \
  --restart unless-stopped \
  pounce-backend:latest

docker network connect n0488s44osgoow4wgo04ogg0 pounce-backend 2>/dev/null || true
echo "✅ Backend deployed"
'
BACKEND_DEPLOY
fi

# Sync and build frontend
if [ "$DEPLOY_FRONTEND" = true ]; then
    log "Syncing frontend code..."
    rsync -avz --delete \
        -e "ssh -i $SSH_KEY -o StrictHostKeyChecking=no" \
        --exclude 'node_modules' \
        --exclude '.next' \
        --exclude '.git' \
        frontend/ \
        ${SSH_USER}@${SERVER}:${REMOTE_REPO}/frontend/

    log "Building frontend image..."
    ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no ${SSH_USER}@${SERVER} \
        "printf '%s\n' \"${DEPLOY_SUDO_PASSWORD}\" | sudo -S docker build --build-arg NEXT_PUBLIC_API_URL=https://api.pounce.ch --build-arg BACKEND_URL=http://pounce-backend:8000 -t pounce-frontend:latest ${REMOTE_REPO}/frontend/" || error "Frontend build failed"

    log "Deploying frontend container..."
    ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no ${SSH_USER}@${SERVER} << FRONTEND_DEPLOY
printf '%s\n' "${DEPLOY_SUDO_PASSWORD}" | sudo -S bash -c '
set -e
docker stop pounce-frontend 2>/dev/null || true
docker rm pounce-frontend 2>/dev/null || true

docker run -d \
  --name pounce-frontend \
  --network coolify \
  --restart unless-stopped \
  --label "traefik.enable=true" \
  --label "traefik.http.routers.pounce-web.rule=Host(\`pounce.ch\`) || Host(\`www.pounce.ch\`)" \
  --label "traefik.http.routers.pounce-web.entryPoints=https" \
  --label "traefik.http.routers.pounce-web.tls=true" \
  --label "traefik.http.routers.pounce-web.tls.certresolver=letsencrypt" \
  --label "traefik.http.services.pounce-web.loadbalancer.server.port=3000" \
  pounce-frontend:latest

docker network connect n0488s44osgoow4wgo04ogg0 pounce-frontend 2>/dev/null || true
echo "✅ Frontend deployed"
'
FRONTEND_DEPLOY
fi

# Health check
log "Running health check..."
sleep 15
curl -sf https://api.pounce.ch/api/v1/health && echo "" && log "Backend: ✅ Healthy"
curl -sf https://pounce.ch -o /dev/null && log "Frontend: ✅ Healthy"

# Cleanup
log "Cleaning up..."
ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no ${SSH_USER}@${SERVER} \
    "printf '%s\n' \"${DEPLOY_SUDO_PASSWORD}\" | sudo -S docker image prune -f" > /dev/null 2>&1

log "=========================================="
log "🎉 DEPLOYMENT SUCCESSFUL!"
log "=========================================="
log "Frontend: https://pounce.ch"
log "Backend:  https://api.pounce.ch"
log "=========================================="
