#!/usr/bin/env bash
set -e

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

echo "=== Agentic Research App ==="
echo ""

# ── Check pre-requisites ─────────────────────────────
check_cmd() {
  if ! command -v "$1" &>/dev/null; then
    echo "ERROR: $1 not found. Please install first." >&2
    exit 1
  fi
}

check_cmd python3
check_cmd podman
check_cmd podman-compose

# ── Python venv ─────────────────────────

if [ ! -d "venv" ]; then
  echo "[1/6] Creating Python virtual environment..."
  python3 -m venv venv
fi
source venv/bin/activate

echo "[2/6] Installing Python dependencies..."
pip install -q -e . 2>&1 | tail -1

# ── Environment ─────────────────────────

if [ ! -f ".env" ]; then
  echo "[3/6] Creating .env from .env.example..."
  cp .env.example .env
fi

# ── Start PostgreSQL + pgvector via Podman ──────────────

echo "[4/6] Starting PostgreSQL + pgvector..."
podman-compose -f podman-compose.yml up -d postgres 2>&1 | tail -1

# Wait for PostgreSQL to be ready
echo "  Waiting for PostgreSQL..."
for i in $(seq 1 30); do
  if podman exec agentic-research-pg pg_isready -U research -d research &>/dev/null; then
    echo "  PostgreSQL ready!"
    break
  fi
  sleep 1
done

# ── Start Marker API ───────────────────────

echo "[5/6] Starting Marker API with deepseek-ocr..."
podman-compose -f podman-compose.yml up -d marker-api 2>&1 | tail -1

# ── Start App ─────────────────────────

echo "[6/6] Starting Agentic Research App..."
podman-compose -f podman-compose.yml up -d app 2>&1 | tail -1

echo ""
echo "=== Agentic Research App is running ==="
echo "  UI:      http://localhost:8000"
echo "  Docs:    http://localhost:8000/docs"
echo "  Marker:  http://localhost:8001/docs"
echo ""
echo "To stop: podman-compose -f podman-compose.yml down"
