#!/usr/bin/env bash
# =================================================================
# LLMHosts — Customer Install Script (Linux / macOS)
# =================================================================
# One command to go from nothing to running AI infrastructure:
#
#   curl -fsSL https://llmhosts.com/install | sh
#
# What this does:
#   1. Kills any running llmhosts process
#   2. Installs uv (Python package manager) if not present
#   3. Installs Python via uv if not present
#   4. Installs llmhosts via uv (isolated, on PATH, no venv confusion)
#   5. Runs "llmhosts up" (detects GPU, installs Ollama, pulls model,
#      starts proxy, authenticates, registers device)
#
# Options (environment variables):
#   LLMHOSTS_VERSION  — Pin a specific version (default: latest)
#   LLMHOSTS_NO_RUN   — Set to 1 to install only, don't run "llmhosts up"
#   LLMHOSTS_FROM_GIT — Set to 1 to install from GitHub main (dev builds)
#   LLMHOSTS_BRANCH   — Git branch to install from (default: main)
# =================================================================
set -euo pipefail

# --- Colors (skip if not a terminal) ---
if [ -t 1 ]; then
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    YELLOW='\033[1;33m'
    BOLD='\033[1m'
    NC='\033[0m'
else
    RED='' GREEN='' YELLOW='' BOLD='' NC=''
fi

log()   { printf "${GREEN}[llmhosts]${NC} %s\n" "$*"; }
warn()  { printf "${YELLOW}[llmhosts]${NC} %s\n" "$*"; }
error() { printf "${RED}[llmhosts]${NC} %s\n" "$*" >&2; }

# --- Configuration ---
LLMHOSTS_VERSION="${LLMHOSTS_VERSION:-}"
LLMHOSTS_NO_RUN="${LLMHOSTS_NO_RUN:-0}"
LLMHOSTS_FROM_GIT="${LLMHOSTS_FROM_GIT:-0}"
LLMHOSTS_BRANCH="${LLMHOSTS_BRANCH:-}"

echo ""
printf "${BOLD}  LLMHosts${NC} — Your hardware. Real AI infrastructure. From anywhere.\n"
echo ""

# --- Step 0: Kill any running llmhosts processes ---
if pgrep -f "llmhosts" > /dev/null 2>&1; then
    warn "Stopping running llmhosts process..."
    pkill -f "llmhosts" 2>/dev/null || true
    sleep 1
    log "Previous llmhosts process stopped"
fi

# --- Step 1: Ensure uv exists (install if not) ---
if command -v uv &>/dev/null; then
    log "uv: $(uv --version)"
else
    log "Installing uv (fast Python package manager)..."
    curl -LsSf https://astral.sh/uv/install.sh | sh

    # Source the env so uv is on PATH in this session
    for envfile in "$HOME/.local/bin/env" "$HOME/.cargo/env"; do
        if [ -f "$envfile" ]; then
            . "$envfile"
        fi
    done
    export PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH"

    if ! command -v uv &>/dev/null; then
        error "uv installation succeeded but 'uv' not found on PATH."
        error "Try: export PATH=\"\$HOME/.local/bin:\$PATH\" && re-run this script."
        exit 1
    fi
    log "uv: $(uv --version) (just installed)"
fi

# --- Step 2: Ensure Python 3.10+ exists ---
PYTHON=""
for cmd in python3 python; do
    if command -v "$cmd" &>/dev/null; then
        version=$("$cmd" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null || echo "0.0")
        major=$(echo "$version" | cut -d. -f1)
        minor=$(echo "$version" | cut -d. -f2)
        if [ "$major" -ge 3 ] && [ "$minor" -ge 10 ]; then
            PYTHON="$cmd"
            break
        fi
    fi
done

if [ -z "$PYTHON" ]; then
    log "No Python 3.10+ found. Installing Python 3.12 via uv..."
    uv python install 3.12
    PYTHON="python3"

    # Verify it worked
    if ! "$PYTHON" -c "import sys; assert sys.version_info >= (3, 10)" 2>/dev/null; then
        error "Python installation failed. Install manually:"
        echo "  macOS:   brew install python@3.12"
        echo "  Ubuntu:  sudo apt install python3"
        echo "  Fedora:  sudo dnf install python3"
        exit 1
    fi
fi

log "Python: $($PYTHON --version)"

# --- Step 3: Install llmhosts ---
if [ "$LLMHOSTS_FROM_GIT" = "1" ] || [ -n "$LLMHOSTS_BRANCH" ]; then
    ref="${LLMHOSTS_BRANCH:-main}"
    log "Installing llmhosts from GitHub ($ref)..."
    uv tool install --force "llmhosts @ git+https://github.com/LookNoHandsMom/LLMHosts.com.git@${ref}"
elif [ -n "$LLMHOSTS_VERSION" ]; then
    log "Installing llmhosts==$LLMHOSTS_VERSION..."
    uv tool install --force "llmhosts==$LLMHOSTS_VERSION"
else
    log "Installing llmhosts (latest from PyPI)..."
    uv tool install --force llmhosts
fi

# Ensure tool bin is on PATH
export PATH="$HOME/.local/bin:$PATH"

if ! command -v llmhosts &>/dev/null; then
    error "llmhosts installed but not found on PATH."
    error "Restart your terminal and run: llmhosts up"
    exit 1
fi

INSTALLED_VERSION=$(llmhosts --version 2>/dev/null || echo "unknown")
log "llmhosts: $INSTALLED_VERSION"

# --- Step 4: Run llmhosts up ---
if [ "$LLMHOSTS_NO_RUN" = "1" ]; then
    echo ""
    log "Installed successfully. Run when ready:"
    echo "  llmhosts up"
    echo ""
else
    echo ""
    log "Starting LLMHosts..."
    echo ""
    exec llmhosts up
fi
