#!/usr/bin/env bash
# scripts/deploy.sh
# -----------------
# Full manual deployment on a Linux server (no Docker).
# Idempotent — safe to re-run to update an existing installation.
#
# What it does:
#   1. Check prerequisites (Python 3.11+, Node 18+)
#   2. Create / update Python virtual environment
#   3. Install Python dependencies
#   4. Build the Vite frontend
#   5. Copy .env.example → .env if no .env exists yet
#   6. (Optional) install the systemd service
#
# Usage:
#   cd /opt/mercator            # or wherever the repo is checked out
#   bash scripts/deploy.sh
#   bash scripts/deploy.sh --with-systemd   # also install systemd service

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
VENV="$REPO_ROOT/.venv"
WITH_SYSTEMD=false

for arg in "$@"; do
    [[ "$arg" == "--with-systemd" ]] && WITH_SYSTEMD=true
done

log() { echo; echo "==> $*"; }
die() { echo "[ERROR] $*" >&2; exit 1; }

# ── 1. Prerequisites ─────────────────────────────────────────────────────────

log "Checking prerequisites..."

PYTHON=$(command -v python3 || true)
[[ -z "$PYTHON" ]] && die "python3 not found. Install Python 3.11+."

PY_VERSION=$("$PYTHON" -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')
PY_MAJOR=$(echo "$PY_VERSION" | cut -d. -f1)
PY_MINOR=$(echo "$PY_VERSION" | cut -d. -f2)
[[ "$PY_MAJOR" -lt 3 || ( "$PY_MAJOR" -eq 3 && "$PY_MINOR" -lt 11 ) ]] && \
    die "Python 3.11+ required (found $PY_VERSION)."
echo "  Python $PY_VERSION — OK"

NODE=$(command -v node || true)
[[ -z "$NODE" ]] && die "node not found. Install Node.js 18+."
NODE_VERSION=$(node --version | sed 's/v//')
NODE_MAJOR=$(echo "$NODE_VERSION" | cut -d. -f1)
[[ "$NODE_MAJOR" -lt 18 ]] && die "Node.js 18+ required (found $NODE_VERSION)."
echo "  Node.js $NODE_VERSION — OK"

NPM=$(command -v npm || true)
[[ -z "$NPM" ]] && die "npm not found."
echo "  npm $(npm --version) — OK"

# ── 2. Python virtual environment ────────────────────────────────────────────

log "Setting up Python virtual environment..."
cd "$REPO_ROOT"

if [[ ! -d "$VENV" ]]; then
    python3 -m venv "$VENV"
    echo "  Created $VENV"
else
    echo "  Reusing $VENV"
fi

# ── 3. Python dependencies ───────────────────────────────────────────────────

log "Installing Python dependencies..."
"$VENV/bin/pip" install --quiet --upgrade pip
"$VENV/bin/pip" install --quiet -r "$REPO_ROOT/requirements.txt"
echo "  Done."

# ── 4. Frontend build ────────────────────────────────────────────────────────

log "Building Vite frontend..."
bash "$REPO_ROOT/scripts/build_frontend.sh"

# ── 5. Environment file ──────────────────────────────────────────────────────

log "Environment file..."
if [[ ! -f "$REPO_ROOT/.env" ]]; then
    cp "$REPO_ROOT/.env.example" "$REPO_ROOT/.env"
    echo "  Created .env from .env.example — edit it now and set OPENAI_API_KEY."
else
    echo "  .env already exists — not overwritten."
fi

# ── 6. Systemd service (optional) ────────────────────────────────────────────

if $WITH_SYSTEMD; then
    log "Installing systemd service..."
    SERVICE_SRC="$REPO_ROOT/scripts/mercator.service"
    SERVICE_DST="/etc/systemd/system/mercator.service"

    [[ ! -f "$SERVICE_SRC" ]] && die "Service file not found: $SERVICE_SRC"

    # Patch the WorkingDirectory and ExecStart paths in a tmp copy
    TMP=$(mktemp)
    sed \
        -e "s|__REPO_ROOT__|$REPO_ROOT|g" \
        -e "s|__VENV__|$VENV|g" \
        "$SERVICE_SRC" > "$TMP"

    sudo cp "$TMP" "$SERVICE_DST"
    rm "$TMP"
    sudo systemctl daemon-reload
    sudo systemctl enable mercator
    echo "  Service installed → $SERVICE_DST"
    echo "  Start with: sudo systemctl start mercator"
else
    echo
    echo "────────────────────────────────────────────────────────"
    echo " Deployment ready.  Next steps:"
    echo
    echo "  1. Edit .env and set OPENAI_API_KEY (minimum required)"
    echo "  2. Start the server:"
    echo "       source .venv/bin/activate"
    echo "       uvicorn api:app --host 0.0.0.0 --port 8000"
    echo
    echo "  Or with systemd (re-run with --with-systemd):"
    echo "       bash scripts/deploy.sh --with-systemd"
    echo "────────────────────────────────────────────────────────"
fi
