# Source this script to create/activate a local venv and install this repo
# in editable mode so the `daycog` CLI is available from your shell.

_DAYCOG_SOURCED=0
if [ -n "${BASH_SOURCE:-}" ]; then
  if [ "${BASH_SOURCE[0]}" != "$0" ]; then
    _DAYCOG_SOURCED=1
  fi
elif [ -n "${ZSH_VERSION:-}" ]; then
  case "${ZSH_EVAL_CONTEXT:-}" in
    *:file|file)
      _DAYCOG_SOURCED=1
      ;;
  esac
fi

if [ "$_DAYCOG_SOURCED" -ne 1 ]; then
  echo "This script must be sourced: source ./activate" >&2
  exit 1
fi

if [ -n "${BASH_SOURCE:-}" ]; then
  _DAYCOG_SOURCE=${BASH_SOURCE[0]}
elif [ -n "${ZSH_VERSION:-}" ]; then
  _DAYCOG_SOURCE=${(%):-%x}
else
  _DAYCOG_SOURCE=$0
fi

_DAYCOG_ACTIVATE_DIR=$(
  cd -- "$(dirname -- "$_DAYCOG_SOURCE")" >/dev/null 2>&1 && pwd
)

if [ -z "$_DAYCOG_ACTIVATE_DIR" ]; then
  echo "Could not determine repo directory for activate" >&2
  return 1
fi

_DAYCOG_VENV_DIR="$_DAYCOG_ACTIVATE_DIR/.venv"

_daycog_distribution_is_editable_from_repo() {
  python - "$1" <<'PY' >/dev/null 2>&1
import pathlib
import subprocess
import sys

repo_root = pathlib.Path(sys.argv[1]).resolve()
proc = subprocess.run(
    [sys.executable, "-m", "pip", "show", "daylily-auth-cognito"],
    capture_output=True,
    text=True,
)
if proc.returncode != 0:
    raise SystemExit(1)

editable_location = None
for line in proc.stdout.splitlines():
    if line.startswith("Editable project location:"):
        editable_location = line.split(":", 1)[1].strip()
        break

if not editable_location:
    raise SystemExit(1)

raise SystemExit(0 if pathlib.Path(editable_location).resolve() == repo_root else 1)
PY
}

_daycog_distribution_requires_expected_cli_core_yo() {
  PYTHONPATH="" python - "$_DAYCOG_ACTIVATE_DIR/pyproject.toml" <<'PY' >/dev/null 2>&1
import importlib.metadata
import sys
import tomllib
from pathlib import Path

from packaging.requirements import Requirement
from packaging.version import Version

pyproject_path = Path(sys.argv[1])
try:
    installed = importlib.metadata.version("cli-core-yo")
except importlib.metadata.PackageNotFoundError:
    raise SystemExit(1)

try:
    pyproject_data = tomllib.loads(pyproject_path.read_text(encoding="utf-8"))
    dependency = next(
        requirement_text
        for requirement_text in pyproject_data["project"]["dependencies"]
        if Requirement(requirement_text).name == "cli-core-yo"
    )
    requirement = Requirement(dependency)
except (KeyError, OSError, StopIteration, tomllib.TOMLDecodeError, ValueError):
    raise SystemExit(1)

raise SystemExit(
    0 if not requirement.specifier or Version(installed) in requirement.specifier else 1
)
PY
}

_daycog_distribution_has_resolved_version() {
  python -I - <<'PY' >/dev/null 2>&1
import importlib.metadata

try:
    version = importlib.metadata.version("daylily-auth-cognito").strip()
except importlib.metadata.PackageNotFoundError:
    raise SystemExit(1)

raise SystemExit(0 if version and version != "0.0.0" else 1)
PY
}

if [ ! -x "$_DAYCOG_VENV_DIR/bin/python" ]; then
  echo "Creating virtual environment at $_DAYCOG_VENV_DIR"
  if ! command -v python3.12 >/dev/null 2>&1; then
    echo "python3.12 not found on PATH" >&2
    return 1
  fi
  if ! python3.12 -m venv "$_DAYCOG_VENV_DIR"; then
    echo "Failed to create virtual environment" >&2
    return 1
  fi
fi

# shellcheck disable=SC1090
if ! . "$_DAYCOG_VENV_DIR/bin/activate"; then
  echo "Failed to activate venv at $_DAYCOG_VENV_DIR" >&2
  return 1
fi

echo "Ensuring pip/setuptools/wheel/setuptools-scm/build support editable installs..."
if ! python -m pip install --upgrade pip setuptools wheel setuptools-scm build >/dev/null; then
  echo "Failed to install pip/setuptools/wheel/setuptools-scm/build" >&2
  return 1
fi

_DAYCOG_NEEDS_INSTALL=0
if ! _daycog_distribution_is_editable_from_repo "$_DAYCOG_ACTIVATE_DIR"; then
  _DAYCOG_NEEDS_INSTALL=1
fi
if ! _daycog_distribution_has_resolved_version; then
  _DAYCOG_NEEDS_INSTALL=1
fi
if ! _daycog_distribution_requires_expected_cli_core_yo; then
  _DAYCOG_NEEDS_INSTALL=1
fi
if ! python -c "import pytest" >/dev/null 2>&1; then
  _DAYCOG_NEEDS_INSTALL=1
fi
if ! python -c "import build" >/dev/null 2>&1; then
  _DAYCOG_NEEDS_INSTALL=1
fi
if ! python -c "import setuptools_scm" >/dev/null 2>&1; then
  _DAYCOG_NEEDS_INSTALL=1
fi

if [ "$_DAYCOG_NEEDS_INSTALL" = "1" ]; then
  echo "Installing daylily-auth-cognito in editable mode..."
  if ! python -m pip install --no-build-isolation -e "${_DAYCOG_ACTIVATE_DIR}[dev]"; then
    echo "Editable install failed" >&2
    return 1
  fi
  if ! _daycog_distribution_is_editable_from_repo "$_DAYCOG_ACTIVATE_DIR"; then
    echo "daylily-auth-cognito is not installed editable from $_DAYCOG_ACTIVATE_DIR" >&2
    return 1
  fi
fi

echo "daycog is ready: $(command -v daycog)"

if [ "${DAYCOG_INSTALL_COMPLETION:-1}" = "1" ]; then
  echo "Installing shell completion (set DAYCOG_INSTALL_COMPLETION=0 to skip)..."
  if ! daycog --install-completion >/dev/null 2>&1; then
    echo "Warning: unable to install completion automatically." >&2
  fi
fi

# Wrap daycog so `daycog setup` can update the caller shell environment.
daycog() {
  _DAYCOG_CAPTURE_CMD=""
  _DAYCOG_SCAN_EXPECTS_CONFIG_VALUE=0
  for _DAYCOG_SCAN_ARG in "$@"; do
    if [ "$_DAYCOG_SCAN_EXPECTS_CONFIG_VALUE" = "1" ]; then
      _DAYCOG_SCAN_EXPECTS_CONFIG_VALUE=0
      continue
    fi
    case "$_DAYCOG_SCAN_ARG" in
      --config)
        _DAYCOG_SCAN_EXPECTS_CONFIG_VALUE=1
        continue
        ;;
      --config=*)
        continue
        ;;
      -*)
        continue
        ;;
      *)
        _DAYCOG_CAPTURE_CMD="$_DAYCOG_SCAN_ARG"
        break
        ;;
    esac
  done

  if [ "$_DAYCOG_CAPTURE_CMD" = "setup" ] || [ "$_DAYCOG_CAPTURE_CMD" = "setup-with-google" ]; then
    _DAYCOG_SETUP_OUT="$(command daycog "$@" --print-exports)"
    _DAYCOG_SETUP_RC=$?
    printf "%s\n" "$_DAYCOG_SETUP_OUT"
    if [ "$_DAYCOG_SETUP_RC" -eq 0 ]; then
      _DAYCOG_EXPORTS="$(printf "%s\n" "$_DAYCOG_SETUP_OUT" | sed -n '/^export /p')"
      if [ -n "$_DAYCOG_EXPORTS" ]; then
        eval "$_DAYCOG_EXPORTS"
      fi
    fi
    _DAYCOG_RETURN_RC=$_DAYCOG_SETUP_RC
    _DAYCOG_FINAL_RC=$_DAYCOG_RETURN_RC
    unset _DAYCOG_EXPORTS
    unset _DAYCOG_RETURN_RC
    unset _DAYCOG_SETUP_OUT
    unset _DAYCOG_SETUP_RC
    unset _DAYCOG_CAPTURE_CMD
    unset _DAYCOG_SCAN_ARG
    unset _DAYCOG_SCAN_EXPECTS_CONFIG_VALUE
    return "$_DAYCOG_FINAL_RC"
  fi

  unset _DAYCOG_CAPTURE_CMD
  unset _DAYCOG_SCAN_ARG
  unset _DAYCOG_SCAN_EXPECTS_CONFIG_VALUE
  command daycog "$@"
}

unset _DAYCOG_ACTIVATE_DIR
unset _DAYCOG_SOURCE
unset _DAYCOG_SOURCED
unset _DAYCOG_VENV_DIR
unset _DAYCOG_NEEDS_INSTALL
unset -f _daycog_distribution_is_editable_from_repo
unset -f _daycog_distribution_has_resolved_version
unset -f _daycog_distribution_requires_expected_cli_core_yo
