#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
TMB_REL="$(basename "$SCRIPT_DIR")"

cd "$PROJECT_ROOT"

# Ensure uv is available
if ! command -v uv &> /dev/null; then
    echo "[TMB] Installing uv (Python package manager)..."
    curl -LsSf https://astral.sh/uv/install.sh | sh
    export PATH="$HOME/.local/bin:$PATH"
    if ! command -v uv &> /dev/null; then
        echo "[TMB] ERROR: Failed to install uv. Install manually: https://docs.astral.sh/uv/"
        exit 1
    fi
    echo "[TMB] uv installed successfully."
    echo
fi

echo "[TMB] Installing into $(basename "$PROJECT_ROOT")/ (developer mode)"
echo

if [ ! -f pyproject.toml ]; then
    PROJECT_NAME="$(basename "$PROJECT_ROOT")"
    cat > pyproject.toml <<TOML
[project]
name = "$PROJECT_NAME"
version = "0.1.0"
requires-python = ">=3.13"
dependencies = [
    "trustmybot",
]

[tool.uv]
package = false

[tool.uv.sources]
trustmybot = { path = "./$TMB_REL", editable = true }
TOML
    echo "  Created pyproject.toml"
fi

if [ ! -f .python-version ]; then
    uv python pin 3.13 > /dev/null 2>&1 || true
fi

uv sync 2>&1 | tail -1
echo

echo "[TMB] Ready (developer mode). Commands:"
echo "  uv run bot               # or: uv run bro, uv run tmb"
echo
