#!/bin/bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

usage() {
    cat <<EOF
Usage: $(basename "$0") [OPTIONS]

Azaion AI Training — Deployment orchestrator.

Options:
  --rollback    Rollback to previous image tags
  --local       Run locally (skip SSH, default if DEPLOY_HOST is unset)
  --help        Show this help message

Environment:
  DEPLOY_HOST   Target server for remote deployment (optional)
  DEPLOY_USER   SSH user (default: deploy)
EOF
    exit 0
}

ROLLBACK=false
LOCAL=false

for arg in "$@"; do
    case "$arg" in
        --rollback) ROLLBACK=true ;;
        --local) LOCAL=true ;;
        --help) usage ;;
        *) echo "Unknown option: $arg"; usage ;;
    esac
done

if [[ -f "$PROJECT_ROOT/.env" ]]; then
    set -a
    source "$PROJECT_ROOT/.env"
    set +a
fi

DEPLOY_HOST="${DEPLOY_HOST:-}"
DEPLOY_USER="${DEPLOY_USER:-deploy}"

if [[ -z "$DEPLOY_HOST" ]]; then
    LOCAL=true
fi

run_cmd() {
    if [[ "$LOCAL" == true ]]; then
        bash -c "$1"
    else
        ssh "${DEPLOY_USER}@${DEPLOY_HOST}" "$1"
    fi
}

run_script() {
    local script="$1"
    shift
    if [[ "$LOCAL" == true ]]; then
        bash "$SCRIPT_DIR/$script" "$@"
    else
        ssh "${DEPLOY_USER}@${DEPLOY_HOST}" "cd /opt/azaion-training && bash scripts/$script $*"
    fi
}

echo "=== Azaion AI Training — Deploy ==="
echo "Mode: $(if $LOCAL; then echo 'local'; else echo "remote ($DEPLOY_HOST)"; fi)"
echo "Action: $(if $ROLLBACK; then echo 'rollback'; else echo 'deploy'; fi)"
echo ""

"$SCRIPT_DIR/generate-config.sh"

if [[ "$ROLLBACK" == true ]]; then
    PREV_TAGS="$SCRIPT_DIR/.previous-tags"
    if [[ ! -f "$PREV_TAGS" ]]; then
        echo "ERROR: No previous tags found at $PREV_TAGS — cannot rollback"
        exit 1
    fi
    echo "Rolling back to previous image tags..."
    set -a
    source "$PREV_TAGS"
    set +a
fi

echo "[1/4] Pulling images..."
run_script pull-images.sh

echo "[2/4] Stopping services..."
run_script stop-services.sh

echo "[3/4] Starting services..."
run_script start-services.sh

echo "[4/4] Checking health..."
if run_script health-check.sh; then
    echo ""
    echo "=== Deploy successful ==="
else
    echo ""
    echo "=== Health check FAILED ==="
    echo "Run: $0 --rollback"
    exit 1
fi
