#!/usr/bin/env bash
# ============================================================================
# EasyClaw Agentic Installer — Bootstrap Script
#
# Usage:
#   curl -fsSL https://easyclaw.help/install.sh | bash
#   # — or —
#   wget -qO- https://easyclaw.help/install.sh | bash
#
# What it does:
#   1. Checks for root (or elevates with sudo)
#   2. Finds Python >= 3.10 (installs via apt if missing)
#   3. Installs pipx (or pip --user fallback)
#   4. Installs the easyclaw-installer package from PyPI
#   5. Launches the agentic TUI installer
# ============================================================================
set -euo pipefail

PACKAGE="easyclaw-installer"
COMMAND="easyclaw-install"
MIN_PYTHON="3.10"
INSTALL_DIR="/opt/easyclaw-installer"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

info()  { echo -e "${CYAN}[INFO]${NC} $*"; }
ok()    { echo -e "${GREEN}[ OK ]${NC} $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC} $*"; }
error() { echo -e "${RED}[FAIL]${NC} $*" >&2; }
die()   { error "$@"; exit 1; }

# ── Root check ──────────────────────────────────────────────────────────────
if [ "$(id -u)" -ne 0 ]; then
    if command -v sudo >/dev/null 2>&1; then
        warn "Not root — re-running with sudo..."
        exec sudo bash "$0" "$@"
    fi
    die "This script must be run as root."
fi
ok "Running as root"

# ── OS check ────────────────────────────────────────────────────────────────
if [ ! -f /etc/os-release ]; then
    die "Cannot detect OS — /etc/os-release not found"
fi
. /etc/os-release
info "Detected: $PRETTY_NAME"

# ── Find or install Python >= 3.10 ──────────────────────────────────────────
find_python() {
    for candidate in python3.12 python3.11 python3.10 python3; do
        if command -v "$candidate" >/dev/null 2>&1; then
            local ver
            ver=$("$candidate" -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')
            local major minor
            major=$(echo "$ver" | cut -d. -f1)
            minor=$(echo "$ver" | cut -d. -f2)
            if [ "$major" -ge 3 ] && [ "$minor" -ge 10 ]; then
                echo "$candidate"
                return 0
            fi
        fi
    done
    return 1
}

PYTHON=""
if PYTHON=$(find_python); then
    ok "Found Python: $PYTHON ($($PYTHON --version))"
else
    info "Python >= $MIN_PYTHON not found — installing..."
    if command -v apt-get >/dev/null 2>&1; then
        apt-get update -qq
        apt-get install -y -qq python3 python3-pip python3-venv
        PYTHON=$(find_python) || die "Failed to install Python >= $MIN_PYTHON"
        ok "Installed $($PYTHON --version)"
    elif command -v dnf >/dev/null 2>&1; then
        die "Detected RHEL/Fedora (dnf). EasyClaw currently requires Ubuntu/Debian.
       Install Python >= $MIN_PYTHON manually, then re-run this script."
    elif command -v yum >/dev/null 2>&1; then
        die "Detected CentOS/RHEL (yum). EasyClaw currently requires Ubuntu/Debian.
       Install Python >= $MIN_PYTHON manually, then re-run this script."
    elif command -v apk >/dev/null 2>&1; then
        die "Detected Alpine Linux (apk). EasyClaw currently requires Ubuntu/Debian.
       Install Python >= $MIN_PYTHON manually, then re-run this script."
    elif command -v pacman >/dev/null 2>&1; then
        die "Detected Arch Linux (pacman). EasyClaw currently requires Ubuntu/Debian.
       Install Python >= $MIN_PYTHON manually, then re-run this script."
    else
        die "No supported package manager found. Please install Python >= $MIN_PYTHON manually, then re-run."
    fi
fi

# ── Create venv and install package ─────────────────────────────────────────
info "Setting up installer at $INSTALL_DIR ..."
mkdir -p "$INSTALL_DIR"

if [ ! -d "$INSTALL_DIR/.venv" ]; then
    info "Creating virtual environment..."
    "$PYTHON" -m venv "$INSTALL_DIR/.venv"
    ok "Venv created"
else
    ok "Venv already exists"
fi

VENV_PIP="$INSTALL_DIR/.venv/bin/pip"
VENV_PYTHON="$INSTALL_DIR/.venv/bin/python"

info "Installing $PACKAGE ..."
"$VENV_PIP" install --upgrade pip -q
"$VENV_PIP" install --upgrade "$PACKAGE" -q
ok "$PACKAGE installed"

# ── Symlink the command ─────────────────────────────────────────────────────
VENV_CMD="$INSTALL_DIR/.venv/bin/$COMMAND"
if [ -f "$VENV_CMD" ]; then
    ln -sf "$VENV_CMD" "/usr/local/bin/$COMMAND"
    ok "Linked $COMMAND → /usr/local/bin/"
fi

# ── Launch ──────────────────────────────────────────────────────────────────
echo ""
echo -e "${GREEN}════════════════════════════════════════════${NC}"
echo -e "${GREEN}  EasyClaw Installer ready!${NC}"
echo -e "${GREEN}  Launching agentic TUI...${NC}"
echo -e "${GREEN}════════════════════════════════════════════${NC}"
echo ""

exec "$VENV_PYTHON" -m easyclaw_installer "$@"
