#!/bin/bash
# Start doorstop-server, bootstrapping a venv with uv if needed.

REPO_ROOT="/workspace"
VENV_DOORSTOP="$REPO_ROOT/.venv/bin/doorstop-server"
VENV_PY="$REPO_ROOT/.venv/bin/python"
LOG_FILE="/tmp/doorstop-server.log"

bootstrap_doorstop_venv() {
    if [ -x "$VENV_DOORSTOP" ]; then
        return 0
    fi

    echo "Bootstrapping doorstop venv with uv..." >> "$LOG_FILE"

    # Prefer uv if available, fall back to python3 -m venv
    if command -v uv >/dev/null 2>&1; then
        if [ ! -d "$REPO_ROOT/.venv" ]; then
            uv venv --python python3 "$REPO_ROOT/.venv" >> "$LOG_FILE" 2>&1 || return 1
        fi
        uv pip install --python "$VENV_PY" doorstop ruff mypy mkdocs >> "$LOG_FILE" 2>&1 || return 1
    elif command -v python3 >/dev/null 2>&1; then
        if [ ! -x "$VENV_PY" ]; then
            python3 -m venv "$REPO_ROOT/.venv" >> "$LOG_FILE" 2>&1 || return 1
        fi
        "$VENV_PY" -m pip install --upgrade pip setuptools wheel >> "$LOG_FILE" 2>&1 || return 1
        "$VENV_PY" -m pip install doorstop ruff mypy mkdocs >> "$LOG_FILE" 2>&1 || return 1
    else
        echo "ERROR: neither uv nor python3 found; cannot create venv" >> "$LOG_FILE"
        return 1
    fi

    if [ -x "$VENV_DOORSTOP" ]; then
        echo "doorstop-server installed in venv" >> "$LOG_FILE"
        return 0
    fi

    echo "ERROR: doorstop-server entrypoint not found after install" >> "$LOG_FILE"
    return 1
}

# Some generated entrypoints inside the venv may hardcode an absolute shebang
# like /workspace/.venv/bin/python. Ensure that path exists by linking it to
# this repo's venv.
mkdir -p "/workspace" 2>/dev/null || true

bootstrap_doorstop_venv >> "$LOG_FILE" 2>&1 || {
    echo "ERROR: failed to bootstrap doorstop venv" >> "$LOG_FILE"
    exit 1
}

if [ -x "$VENV_PY" ]; then
    if [ ! -e "/workspace/.venv" ]; then
        ln -s "$REPO_ROOT/.venv" "/workspace/.venv" 2>/dev/null || true
    fi
fi

if [ -x "$VENV_DOORSTOP" ]; then
    echo "Starting doorstop-server..." >> "$LOG_FILE"
    cd "$REPO_ROOT" || exit 1
    nohup "$VENV_DOORSTOP" --host 0.0.0.0 --port 17867 >> "$LOG_FILE" 2>&1 &
    PID=$!
    echo "doorstop-server started with PID $PID" >> "$LOG_FILE"

    # Quick sanity check: if it exits immediately, capture that in the log.
    sleep 0.2
    if ps -p "$PID" >/dev/null 2>&1; then
        echo "doorstop-server still running (PID $PID)" >> "$LOG_FILE"
    else
        echo "WARNING: doorstop-server exited immediately (PID $PID)" >> "$LOG_FILE"
    fi
else
    echo "doorstop-server not found at $VENV_DOORSTOP" >> "$LOG_FILE"
fi
