#!/usr/bin/env bash
# ai-chat-exporter — run the exporter without activating a virtualenv.
#
#   cd /path/to/AIChatExporter
#   ./ai-chat-exporter export --provider all
#
# Creates .venv and installs dependencies on first run, so a fresh clone on a
# new machine needs no `python3 -m venv` / `source .venv/bin/activate` ceremony.
# Reinstalls automatically when pyproject.toml changes.
#
# Working directory is deliberately NOT changed: EXPORT_DIR, CACHE_DIR and .env
# discovery are all relative to your current directory, which is what lets the
# same checkout archive different machines into different places. Run it from
# the repo (see the warning below) unless you mean otherwise.
#
# Windows equivalent: ai-chat-exporter.cmd (same directory).

set -euo pipefail

DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
VENV="$DIR/.venv"
PY="$VENV/bin/python"
STAMP="$VENV/.deps-stamp"

# The cache manifest is read from ./cache by default. Running from somewhere
# else silently starts a *new, empty* archive rather than failing, which would
# re-export everything and orphan the existing Joplin notes. Warn, don't block —
# a deliberate second archive is a legitimate thing to want.
if [ "$PWD" != "$DIR" ] && [ -z "${AI_CHAT_EXPORTER_QUIET_CWD:-}" ]; then
    echo "warning: running from $PWD, not $DIR" >&2
    echo "         cache/ and exports/ resolve against the current directory," >&2
    echo "         so this may start a separate archive. Set" >&2
    echo "         AI_CHAT_EXPORTER_QUIET_CWD=1 to silence this." >&2
fi

find_python() {
    for candidate in python3 python; do
        if command -v "$candidate" >/dev/null 2>&1; then
            # Needs >=3.11 (pyproject requires-python).
            if "$candidate" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 11) else 1)' 2>/dev/null; then
                command -v "$candidate"
                return 0
            fi
        fi
    done
    return 1
}

if [ ! -x "$PY" ]; then
    BOOTSTRAP_PY="$(find_python)" || {
        echo "error: no python3 >= 3.11 found on PATH — install it and re-run." >&2
        exit 1
    }
    echo "Creating virtualenv in $VENV …" >&2
    "$BOOTSTRAP_PY" -m venv "$VENV"
    rm -f "$STAMP"
fi

# Install (or refresh) dependencies when the venv is new or pyproject changed.
if [ ! -f "$STAMP" ] || [ "$DIR/pyproject.toml" -nt "$STAMP" ]; then
    echo "Installing dependencies …" >&2
    "$PY" -m pip install --quiet --upgrade pip
    "$PY" -m pip install --quiet -e "$DIR"
    touch "$STAMP"
fi

exec "$PY" -m src.main "$@"
