#!/bin/bash
set -eo pipefail

PROJECT_DIR="${LICOS_PROJECT_PATH:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
cd "$PROJECT_DIR"

ensure_pip_config() {
  mkdir -p "${HOME:-/root}/.pip"
  cat > "${HOME:-/root}/.pip/pip.conf" <<'EOF'
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
extra-index-url = https://pypi.org/simple/
trusted-host = mirrors.aliyun.com
EOF
}

ensure_pip_config

PYTHON_BIN="${PYTHON_BIN:-python}"
if ! command -v "$PYTHON_BIN" >/dev/null 2>&1 && command -v python3 >/dev/null 2>&1; then
  PYTHON_BIN=python3
fi
PIP_PYTHON="$PYTHON_BIN"

GLOBAL_PIP_ARGS=(--no-cache-dir)
if "$PYTHON_BIN" -m pip install --help 2>/dev/null | grep -q -- "--break-system-packages"; then
  GLOBAL_PIP_ARGS+=(--break-system-packages)
fi

ensure_project_venv() {
  local venv_dir="$PROJECT_DIR/.venv"

  if [ -x "$venv_dir/bin/python" ] \
    && "$venv_dir/bin/python" -m pip --version >/dev/null 2>&1 \
    && grep -Eq '^include-system-site-packages[[:space:]]*=[[:space:]]*true$' "$venv_dir/pyvenv.cfg" 2>/dev/null; then
    PIP_PYTHON="$venv_dir/bin/python"
    return
  fi

  rm -rf "$venv_dir"
  echo "[setup] Creating project virtualenv at $venv_dir"
  if ! "$PYTHON_BIN" -m venv --system-site-packages "$venv_dir" >/dev/null 2>&1; then
    echo "[setup] python -m venv unavailable; installing virtualenv fallback"
    "$PYTHON_BIN" -m pip install "${GLOBAL_PIP_ARGS[@]}" virtualenv
    "$PYTHON_BIN" -m virtualenv --system-site-packages "$venv_dir"
  fi

  PIP_PYTHON="$venv_dir/bin/python"
  "$PIP_PYTHON" -m pip --version >/dev/null
}

PIP_ARGS=()
refresh_pip_args() {
  PIP_ARGS=(--no-cache-dir)
  if "$PIP_PYTHON" -m pip install --help 2>/dev/null | grep -q -- "--break-system-packages"; then
    PIP_ARGS+=(--break-system-packages)
  fi
  if [ -n "${PIP_TARGET:-}" ]; then
    PIP_ARGS+=(--target "$PIP_TARGET")
  fi
}

refresh_pip_args

install_pyproject_dependencies_with_pip() {
  if [ -z "${PIP_TARGET:-}" ]; then
    ensure_project_venv
  fi
  refresh_pip_args

  local deps_file
  deps_file="$(mktemp)"
  "$PIP_PYTHON" - "$deps_file" <<'PY'
import sys
import tomllib
from pathlib import Path

deps_path = Path(sys.argv[1])
data = tomllib.loads(Path("pyproject.toml").read_text(encoding="utf-8"))
dependencies = data.get("project", {}).get("dependencies", [])
lines = []
if isinstance(dependencies, list):
    lines = [
        item.strip()
        for item in dependencies
        if isinstance(item, str) and item.strip()
    ]
deps_path.write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8")
PY

  if [ -s "$deps_file" ]; then
    echo "[setup] Pip mode: installing dependencies from pyproject.toml"
    local status=0
    "$PIP_PYTHON" -m pip install "${PIP_ARGS[@]}" -r "$deps_file" || status=$?
    rm -f "$deps_file"
    return "$status"
  else
    echo "[setup] pyproject.toml has no project.dependencies, skipping install"
  fi
  rm -f "$deps_file"
}

if command -v uv >/dev/null 2>&1 && [ -f "pyproject.toml" ]; then
  if [ -n "${PIP_TARGET:-}" ]; then
    echo "[setup] Deploy mode (uv): installing to PIP_TARGET=$PIP_TARGET"
    uv export --frozen --no-hashes --no-dev | uv pip install --no-cache --target "$PIP_TARGET" -r - \
      || install_pyproject_dependencies_with_pip
  else
    echo "[setup] Dev mode (uv): syncing .venv"
    if [ -f "uv.lock" ]; then
      uv sync --frozen || uv sync
    else
      uv sync
    fi
  fi
elif [ -f "pyproject.toml" ]; then
  install_pyproject_dependencies_with_pip
elif [ -f "requirements.txt" ]; then
  if [ -z "${PIP_TARGET:-}" ]; then
    ensure_project_venv
  fi
  refresh_pip_args
  echo "[setup] Fallback mode (pip): installing from requirements.txt"
  "$PIP_PYTHON" -m pip install "${PIP_ARGS[@]}" -r requirements.txt
else
  echo "[setup] no pyproject.toml or requirements.txt found, skipping install"
fi
