#!/usr/bin/env bash
# KULVEX Bootstrap — One command installer.
#
# Usage:
#   curl -fsSL kulvex.ai/install | bash -s -- --license-key klx_lic_xxx
#   curl -fsSL kulvex.ai/install | KULVEX_LICENSE_KEY=klx_lic_xxx bash
#
# Supports: Linux (Ubuntu/Debian/Fedora/RHEL/Arch), macOS, Windows via WSL2.
#
# This script:
#   1. Detects platform (Linux / macOS / WSL2)
#   2. Installs Python 3.10+ and pip if missing
#   3. Installs Rich + httpx (wizard TUI dependencies)
#   4. Downloads the KULVEX source from kulvex.ai
#   5. Writes a launcher script
#   6. Launches the interactive wizard with proper TTY
#
# Zero dependencies required — just curl and bash.

set -euo pipefail

KULVEX_SERVER="${LICENSE_SERVER_URL:-https://kulvex.ai}"
KULVEX_HOME="${KULVEX_HOME:-$HOME/.kulvex}"
KULVEX_KEY="${KULVEX_LICENSE_KEY:-}"
MIN_PYTHON_MAJOR=3
MIN_PYTHON_MINOR=10

# Capture any args passed via: curl ... | bash -s -- --license-key xxx
EXTRA_ARGS=("$@")

# Extract --license-key from args if provided
for i in "${!EXTRA_ARGS[@]}"; do
    if [[ "${EXTRA_ARGS[$i]}" == "--license-key" ]] && [[ -n "${EXTRA_ARGS[$((i+1))]:-}" ]]; then
        KULVEX_KEY="${EXTRA_ARGS[$((i+1))]}"
    fi
done

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m'

info()  { echo -e "${CYAN}ℹ${NC} $*"; }
ok()    { echo -e "${GREEN}✓${NC} $*"; }
warn()  { echo -e "${YELLOW}⚠${NC} $*"; }
error() { echo -e "${RED}✗${NC} $*" >&2; }

echo ""
echo -e "${BOLD}╔══════════════════════════════════════════════╗${NC}"
echo -e "${BOLD}║   KULVEX — Autonomous Intelligence Platform  ║${NC}"
echo -e "${BOLD}╚══════════════════════════════════════════════╝${NC}"
echo ""

# ── Platform detection ───────────────────────────────────
OS="$(uname -s)"
IS_WSL=false

case "$OS" in
    Linux)
        if grep -qi "microsoft\|wsl" /proc/version 2>/dev/null; then
            IS_WSL=true
            info "WSL2 detected — installing for Windows via WSL"
        else
            info "Linux detected"
        fi
        ;;
    Darwin)
        info "macOS detected"
        ;;
    MINGW*|MSYS*|CYGWIN*)
        error "This installer must run inside WSL2, not native Windows."
        echo ""
        echo "  To set up WSL2:"
        echo -e "  1. Open PowerShell as Administrator and run: ${BOLD}wsl --install${NC}"
        echo "  2. Restart your computer"
        echo "  3. Open Ubuntu from the Start menu"
        echo "  4. Run this command inside Ubuntu:"
        echo -e "     ${BOLD}curl -fsSL kulvex.ai/install | bash -s -- --license-key YOUR_KEY${NC}"
        echo ""
        exit 1
        ;;
    *)
        error "Unsupported platform: $OS"
        exit 1
        ;;
esac

# ── Detect package manager ───────────────────────────────
detect_pkg_mgr() {
    if command -v apt-get &>/dev/null; then echo "apt"
    elif command -v dnf &>/dev/null; then echo "dnf"
    elif command -v yum &>/dev/null; then echo "yum"
    elif command -v pacman &>/dev/null; then echo "pacman"
    elif command -v zypper &>/dev/null; then echo "zypper"
    elif command -v brew &>/dev/null; then echo "brew"
    else echo "unknown"
    fi
}

PKG_MGR=$(detect_pkg_mgr)

# ── Install Python 3.10+ if missing ─────────────────────
find_python() {
    for cmd in python3 python; do
        if command -v "$cmd" &>/dev/null; then
            local ver
            ver=$("$cmd" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null || echo "0.0")
            local major="${ver%%.*}"
            local minor="${ver##*.}"
            if [ "$major" -ge "$MIN_PYTHON_MAJOR" ] && [ "$minor" -ge "$MIN_PYTHON_MINOR" ]; then
                echo "$cmd"
                return 0
            fi
        fi
    done
    return 1
}

PYTHON=""
if PYTHON=$(find_python); then
    ok "Python: $($PYTHON --version 2>&1)"
else
    info "Installing Python 3..."
    case "$PKG_MGR" in
        apt)
            sudo apt-get update -qq 2>/dev/null
            sudo apt-get install -y -qq python3 python3-pip python3-venv 2>/dev/null
            ;;
        dnf)
            sudo dnf install -y -q python3 python3-pip 2>/dev/null
            ;;
        yum)
            sudo yum install -y -q python3 python3-pip 2>/dev/null
            ;;
        pacman)
            sudo pacman -Sy --noconfirm python python-pip 2>/dev/null
            ;;
        zypper)
            sudo zypper install -y python3 python3-pip 2>/dev/null
            ;;
        brew)
            brew install python@3 2>/dev/null
            ;;
        *)
            error "Could not detect package manager. Install Python 3.10+ manually."
            exit 1
            ;;
    esac

    if PYTHON=$(find_python); then
        ok "Python installed: $($PYTHON --version 2>&1)"
    else
        error "Could not install Python 3.10+. Install it manually and re-run."
        exit 1
    fi
fi

# ── Install pip if missing ───────────────────────────────
if ! $PYTHON -m pip --version &>/dev/null; then
    info "Installing pip..."
    case "$PKG_MGR" in
        apt)    sudo apt-get install -y -qq python3-pip 2>/dev/null ;;
        dnf)    sudo dnf install -y -q python3-pip 2>/dev/null ;;
        yum)    sudo yum install -y -q python3-pip 2>/dev/null ;;
        pacman) sudo pacman -S --noconfirm python-pip 2>/dev/null ;;
        *)      curl -fsSL https://bootstrap.pypa.io/get-pip.py | $PYTHON 2>/dev/null ;;
    esac

    if $PYTHON -m pip --version &>/dev/null; then
        ok "pip installed"
    else
        warn "pip not available — trying system packages"
    fi
fi

# ── Install wizard dependencies ──────────────────────────
info "Preparing wizard..."
$PYTHON -m pip install --quiet --break-system-packages rich httpx 2>/dev/null || \
$PYTHON -m pip install --quiet --user rich httpx 2>/dev/null || \
$PYTHON -m pip install --quiet rich httpx 2>/dev/null || {
    case "$PKG_MGR" in
        apt)    sudo apt-get install -y -qq python3-rich python3-httpx 2>/dev/null ;;
        dnf)    sudo dnf install -y -q python3-rich python3-httpx 2>/dev/null ;;
        pacman) sudo pacman -S --noconfirm python-rich python-httpx 2>/dev/null ;;
        *)      error "Could not install wizard dependencies (rich, httpx)."; exit 1 ;;
    esac
}
ok "Wizard dependencies ready"

# ── Download KULVEX source from server ────────────────────
mkdir -p "$KULVEX_HOME"

info "Downloading KULVEX..."
curl -fSL --progress-bar "${KULVEX_SERVER}/install/source.tar.gz" | tar -xz -C "$KULVEX_HOME" 2>/dev/null || {
    error "Could not download KULVEX from ${KULVEX_SERVER}"
    error "Check your internet connection and try again."
    exit 1
}
ok "KULVEX downloaded to ${KULVEX_HOME}"

# ── WSL-specific guidance ─────────────────────────────────
if [ "$IS_WSL" = true ]; then
    echo ""
    info "WSL2 note: Docker Desktop for Windows is required."
    info "The wizard will install it automatically if needed."
fi

# ── Write launcher and run wizard with proper TTY ─────────
# When piped via `curl | bash`, stdin is the script itself.
# We write a small launcher script and exec it so bash gets
# a fresh process with /dev/tty as stdin.

LAUNCHER=$(mktemp "${KULVEX_HOME}/.launcher.XXXXXX.sh")
cat > "$LAUNCHER" <<LAUNCHER_EOF
#!/usr/bin/env bash
export LICENSE_SERVER_URL="${KULVEX_SERVER}"
export KULVEX_LICENSE_KEY="${KULVEX_KEY}"
cd "${KULVEX_HOME}"

WIZARD_ARGS=""
[ -n "\${KULVEX_LICENSE_KEY}" ] && WIZARD_ARGS="--license-key \${KULVEX_LICENSE_KEY}"

exec ${PYTHON} "${KULVEX_HOME}/wizard/main.py" \${WIZARD_ARGS} "\$@"
LAUNCHER_EOF
chmod +x "$LAUNCHER"

echo ""
# Run launcher with TTY stdin — this is the key trick
exec bash -c "exec < /dev/tty; exec $LAUNCHER" 2>/dev/null || {
    # Fallback: if /dev/tty is not available (e.g. Docker, CI), run non-interactively
    warn "No interactive terminal detected — running in auto mode"
    exec $PYTHON "${KULVEX_HOME}/wizard/main.py" --auto ${KULVEX_KEY:+--license-key "$KULVEX_KEY"}
}
