#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
STATE_DIR="${ROOT}/.orchestration"
PID_FILE="${STATE_DIR}/pids"
PYTHON="${ROOT}/.venv/bin/python"

if [[ ! -x "${PYTHON}" ]]; then
  echo "Missing venv python at ${PYTHON}"
  exit 1
fi

mkdir -p "${STATE_DIR}"

echo "Starting PostgreSQL (docker)..."
if ! docker ps --format '{{.Names}}' | grep -q '^trading_postgres$'; then
  docker compose up -d postgres
fi

echo "Applying migrations..."
if [[ -f "${ROOT}/alembic.ini" ]]; then
  "${PYTHON}" -m alembic upgrade head
elif [[ -f "${ROOT}/backend/alembic.ini" ]]; then
  "${PYTHON}" -m alembic -c "${ROOT}/backend/alembic.ini" upgrade head
fi
"${PYTHON}" "${ROOT}/backend/scripts/run_migrations.py"

echo "Starting backend..."
(cd "${ROOT}/backend" && PYTHONPATH="${ROOT}:${ROOT}/backend" "${PYTHON}" -m uvicorn app.main:app --reload) &
BACKEND_PID=$!

echo "Starting engine runner..."
(cd "${ROOT}" && PYTHONPATH="${ROOT}:${ROOT}/backend" "${PYTHON}" -m indian_paper_trading_strategy.engine.engine_runner) &
ENGINE_PID=$!

echo "Starting frontend..."
(cd "${ROOT}/frontend" && npm run dev) &
FRONTEND_PID=$!

cat > "${PID_FILE}" <<EOF
backend=${BACKEND_PID}
engine=${ENGINE_PID}
frontend=${FRONTEND_PID}
EOF

echo "Waiting for backend health..."
HEALTH_URL="http://localhost:8000/health"
READY=0
for _ in $(seq 1 60); do
  if curl -fsS "${HEALTH_URL}" >/dev/null 2>&1; then
    READY=1
    break
  fi
  sleep 2
done

if [[ "${READY}" -eq 1 ]]; then
  if command -v xdg-open >/dev/null 2>&1; then
    xdg-open "http://localhost:3000/admin" >/dev/null 2>&1 || true
  elif command -v open >/dev/null 2>&1; then
    open "http://localhost:3000/admin" >/dev/null 2>&1 || true
  else
    echo "Open http://localhost:3000/admin in your browser."
  fi
else
  echo "Backend health check failed. Open http://localhost:3000/admin manually."
fi
