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

resolve_repo() {
  if [[ -n "${OSIRIS_HOME:-}" && -d "$OSIRIS_HOME/src/osiris_cli" ]]; then
    echo "$OSIRIS_HOME"
    return
  fi
  if [[ -d "$PWD/src/osiris_cli" ]]; then
    echo "$PWD"
    return
  fi
  if command -v git >/dev/null 2>&1; then
    root="$(git -C "$PWD" rev-parse --show-toplevel 2>/dev/null || true)"
    if [[ -n "$root" && -d "$root/src/osiris_cli" ]]; then
      echo "$root"
      return
    fi
  fi
  candidate="$HOME/Documents/osiris-cli Workspace"
  if [[ -d "$candidate/src/osiris_cli" ]]; then
    echo "$candidate"
    return
  fi
  script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  echo "$(cd "$script_dir/.." && pwd)"
}

repo_dir="$(resolve_repo)"
if [[ ! -d "$repo_dir/src/osiris_cli" ]]; then
  echo "Error: osiris-cli repo not found. Set OSIRIS_HOME or run from the repo." >&2
  exit 1
fi

venv_python="$repo_dir/.venv/bin/python"
export PYTHONPATH="$repo_dir/src:${PYTHONPATH:-}"

python_has_deps() {
  "$1" - <<'PY'
import importlib.util
mods = ["toml","rich","typer","prompt_toolkit","pydantic","httpx","openai","requests","bs4"]
raise SystemExit(0 if all(importlib.util.find_spec(m) for m in mods) else 1)
PY
}

venv_is_valid() {
  "$venv_python" - <<'PY'
import importlib.util
import sys
mods = ["toml","rich","typer","prompt_toolkit","pydantic","httpx","openai","requests","bs4"]
ok = sys.version_info >= (3, 10) and all(importlib.util.find_spec(m) for m in mods)
raise SystemExit(0 if ok else 1)
PY
}

if [[ -x "$venv_python" ]] && venv_is_valid; then
  exec "$venv_python" -m osiris_cli.main "$@"
fi

if [[ -z "${OSIRIS_NO_BOOTSTRAP:-}" ]]; then
  if [[ -x "$repo_dir/scripts/bootstrap_venv.sh" ]]; then
    "$repo_dir/scripts/bootstrap_venv.sh" || true
  fi
  if [[ -x "$venv_python" ]] && venv_is_valid; then
    exec "$venv_python" -m osiris_cli.main "$@"
  fi
fi

if command -v python3 >/dev/null 2>&1; then
  if python3 - <<'PY'
import sys
sys.exit(0 if sys.version_info >= (3, 10) else 1)
PY
  then
    if python_has_deps python3; then
      exec python3 -m osiris_cli.main "$@"
    fi
  fi
fi

echo "Error: Missing dependencies. Run ./scripts/bootstrap_venv.sh (requires network) or set OSIRIS_HOME to a prepared repo." >&2
exit 1
