#!/usr/bin/env bash
# Wells launcher — runs the harness from the cloned repo, no install needed.
#
# Usage:
#   ./wells "<your goal>"                 # run on this repo
#   ./wells --workspace /path "fix bug"   # run against another project
#   ./wells config                        # interactive settings menu
#   ./wells info                          # show configuration
#
# This wrapper handles the venv automatically. It deliberately AVOIDS building
# the local package (which would need hatchling from PyPI) by running the
# harness module directly with PYTHONPATH=src. It also tells uv to use the
# system certificate store (UV_SYSTEM_CERTS, or UV_NATIVE_TLS on older uv) —
# needed on corporate networks whose proxy presents a self-signed cert that
# Python's bundled certifi rejects.

set -e

# Save the user's CWD before we cd into the repo root.
USER_CWD="$(pwd)"

# Resolve the directory this script lives in (the repo root), independent of CWD.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# Use the OS certificate store so corporate TLS-intercepting proxies work.
# Newer uv renamed UV_NATIVE_TLS to UV_SYSTEM_CERTS (the old name still works
# but prints a deprecation warning) — set whichever this uv understands.
if [ -z "${UV_SYSTEM_CERTS:-}" ] && [ -z "${UV_NATIVE_TLS:-}" ]; then
    if uv sync --help 2>/dev/null | grep -q "UV_SYSTEM_CERTS"; then
        export UV_SYSTEM_CERTS=1
    else
        export UV_NATIVE_TLS=1
    fi
fi

# Sync dependencies WITHOUT building the local package — but only when
# uv.lock actually changed since the last successful sync. A no-op
# `uv sync` still costs ~1s on every launch (full lockfile resolution
# check); skipping it when nothing changed saves that on every invocation,
# not just the first. --no-install-project means uv never invokes the build
# backend (hatchling), so no PyPI fetch is needed for the build step.
STAMP=".venv/.sync-stamp"
LOCK_STAMP="$(stat -c '%Y|%s' uv.lock 2>/dev/null || stat -f '%m|%z' uv.lock 2>/dev/null || echo "")"
CACHED_STAMP=""
[ -f "$STAMP" ] && CACHED_STAMP="$(cat "$STAMP")"

if [ -n "$LOCK_STAMP" ] && [ "$LOCK_STAMP" = "$CACHED_STAMP" ] \
   && { [ -x ".venv/bin/python" ] || [ -x ".venv/Scripts/python.exe" ]; }; then
    :  # uv.lock unchanged and the venv is intact — skip the sync check.
elif ! uv sync --no-install-project --quiet 2>/dev/null; then
    echo "[wells] installing dependencies (first run may take a minute) ..."
    uv sync --no-install-project || {
        echo "[wells] dependency install failed. Check your network/TLS settings." >&2
        echo "[wells] If behind a proxy, try: set SSL_CERT_FILE= and REQUESTS_CA_BUNDLE=" >&2
        exit 1
    }
    echo "$LOCK_STAMP" > "$STAMP"
else
    echo "$LOCK_STAMP" > "$STAMP"
fi

# Install optional semantic-search libraries (fastembed + sqlite-vec) on
# first launch. Best-effort: stamp-file cached so it only runs once per
# pyproject.toml change, skips if the libs already import, and never blocks
# the launch on failure. Set WELLS_NO_EMBEDDINGS=1 to opt out.
if [ "${WELLS_NO_EMBEDDINGS:-}" != "1" ]; then
    EMBED_STAMP=".venv/.embed-stamp"
    EMBED_SPEC="$(stat -c '%Y|%s' pyproject.toml 2>/dev/null || stat -f '%m|%z' pyproject.toml 2>/dev/null || echo "")"
    EMBED_CACHED=""
    [ -f "$EMBED_STAMP" ] && EMBED_CACHED="$(cat "$EMBED_STAMP")"

    if [ -n "$EMBED_SPEC" ] && [ "$EMBED_SPEC" != "$EMBED_CACHED" ]; then
        PYBIN=""
        if [ -x ".venv/bin/python" ]; then PYBIN=".venv/bin/python"
        elif [ -x ".venv/Scripts/python.exe" ]; then PYBIN=".venv/Scripts/python.exe"
        fi

        ALREADY="0"
        if [ -n "$PYBIN" ] && "$PYBIN" -c "import fastembed, sqlite_vec" 2>/dev/null; then
            ALREADY="1"
        fi

        if [ "$ALREADY" != "1" ]; then
            echo ""
            echo "[wells] Installing semantic-search libraries (one-time, ~60s)..."
            echo "[wells]   - fastembed  (local ONNX embeddings, ~150 MB)"
            echo "[wells]   - sqlite-vec (vector storage extension)"
            echo ""
            if uv pip install fastembed sqlite-vec; then
                echo ""
                echo "[wells] Semantic search ready."
                echo ""
            else
                echo "" >&2
                echo "[wells] Semantic-search libraries could not be installed (network/TLS error?)." >&2
                echo "[wells] Wells will start normally; semantic_search will return a hint" >&2
                echo "[wells] to install manually. Other tools are unaffected." >&2
                echo "" >&2
            fi
        fi
        echo "$EMBED_SPEC" > "$EMBED_STAMP"
    fi
fi

# Run the harness directly from src/ — no package build, no install step.
export PYTHONPATH="$SCRIPT_DIR/src${PYTHONPATH:+:$PYTHONPATH}"
export WORKSPACE_ROOT="$USER_CWD"
exec uv run python -m wells.main "$@"
