#!/usr/bin/env bash
# teambot official installer
# Usage:  curl -fsSL https://teambot.samai.cc/install.sh | bash
#   or:   curl -fsSL https://teambot.samai.cc/install.sh | bash -s -- --version 1.52.0
#
# Installs the teambot AI assistant.
# No pip, no npm. Downloads a standalone binary or self-contained package.

set -euo pipefail

# ---- defaults -------------------------------------------------------------
BASE_URL="https://teambot.samai.cc/downloads"
INSTALL_DIR="/usr/local/bin"
BIN_NAME="teambot"
REQUESTED_VERSION=""

# ---- parse args -----------------------------------------------------------
while [[ $# -gt 0 ]]; do
    case "$1" in
        --version) REQUESTED_VERSION="$2"; shift 2 ;;
        --help|-h)
            echo "teambot installer"
            echo "  curl -fsSL https://teambot.samai.cc/install.sh | bash"
            exit 0 ;;
        *) echo "Unknown option: $1" >&2; exit 1 ;;
    esac
done

# ---- helpers --------------------------------------------------------------
info()  { printf '[OK] %s\n' "$*"; }
warn()  { printf '[!] %s\n' "$*" >&2; }
error() { printf '[X] %s\n' "$*" >&2; }
die()   { error "$*"; exit 1; }

# ---- detect OS / arch -----------------------------------------------------
OS="$(uname -s)"
ARCH="$(uname -m)"
case "$OS" in
    Linux*)  PLATFORM_OS="linux" ;;
    Darwin*) PLATFORM_OS="darwin" ;;
    MINGW*|MSYS*|CYGWIN*)
        die "Windows detected. Run in PowerShell: irm https://teambot.samai.cc/install.ps1 | iex" ;;
    *) die "Unsupported OS: $OS" ;;
esac
case "$ARCH" in
    x86_64|amd64)   PLATFORM_ARCH="amd64" ;;
    aarch64|arm64)  PLATFORM_ARCH="arm64" ;;
    *) die "Unsupported architecture: $ARCH" ;;
esac

PLATFORM="${PLATFORM_OS}-${PLATFORM_ARCH}"
info "Detected platform: $PLATFORM"

# ---- pick install dir (sudo or not) --------------------------------------
SUDO=""
if [[ -w "$INSTALL_DIR" ]]; then
    TARGET="${INSTALL_DIR}/${BIN_NAME}"
elif command -v sudo >/dev/null 2>&1 && sudo -n true 2>/dev/null; then
    TARGET="${INSTALL_DIR}/${BIN_NAME}"
    SUDO="sudo"
else
    TARGET="${HOME}/.local/bin/${BIN_NAME}"
    mkdir -p "$(dirname "$TARGET")"
    warn "No sudo access - installing to $TARGET"
fi

# ---- pick version ---------------------------------------------------------
if [[ -z "$REQUESTED_VERSION" ]]; then
    info "Fetching latest version from $BASE_URL/latest-version.txt ..."
    REQUESTED_VERSION="$(curl -fsSL "$BASE_URL/latest-version.txt" | tr -d '[:space:]')"
    [[ -z "$REQUESTED_VERSION" ]] && die "Could not determine latest version."
fi
info "Installing teambot v$REQUESTED_VERSION"

# ---- detect Python --------------------------------------------------------
PY_CMD=""
for cmd in python3.14 python3.13 python3.12 python3.11 python3.10 python3 python; do
    if command -v "$cmd" &>/dev/null; then
        ver="$($cmd -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")' 2>/dev/null)" || continue
        major="$(echo "$ver" | cut -d. -f1)"
        minor="$(echo "$ver" | cut -d. -f2)"
        if [[ "$major" -ge 3 ]] && [[ "$minor" -ge 10 ]]; then
            PY_CMD="$cmd"; break
        fi
    fi
done

# ---- create teambot runtime directory -------------------------------------
TEAMBOT_RUNTIME="${HOME}/.teambot/runtime"
VENV_DIR="${TEAMBOT_RUNTIME}/venv"
mkdir -p "$TEAMBOT_RUNTIME"

# ---- download strategy: try standalone binary first, fallback to wheel ----
TMP_FILE="$(mktemp -t teambot-XXXXXX)"
trap 'rm -f "$TMP_FILE"' EXIT

# Try platform-specific standalone binary
BINARY_FILE="teambot-${PLATFORM}"
BINARY_URL="$BASE_URL/$BINARY_FILE"
BINARY_AVAILABLE=false

info "Checking for standalone binary: $BINARY_FILE ..."
if curl -fsSL --head "$BINARY_URL" 2>/dev/null | grep -q "200"; then
    BINARY_AVAILABLE=true
fi

if $BINARY_AVAILABLE; then
    # Download standalone binary
    info "Downloading standalone binary $BINARY_URL ..."
    if ! curl -fSL --retry 3 --retry-delay 2 -o "$TMP_FILE" "$BINARY_URL"; then
        die "Download failed."
    fi

    # Verify SHA256
    info "Verifying SHA256 checksum ..."
    EXPECTED_HASH="$(curl -fsSL "$BASE_URL/checksums-sha256.txt" | awk -v f="$BINARY_FILE" '$2==f {print $1; exit}')"
    if [[ -n "$EXPECTED_HASH" ]]; then
        ACTUAL_HASH="$(sha256sum "$TMP_FILE" | awk '{print $1}')"
        if [[ "$EXPECTED_HASH" != "$ACTUAL_HASH" ]]; then
            die "Checksum mismatch! expected: $EXPECTED_HASH actual: $ACTUAL_HASH"
        fi
        info "Checksum OK"
    else
        warn "No checksum entry for $BINARY_FILE - skipping verification."
    fi

    # Install binary
    info "Installing to $TARGET ..."
    if [[ -n "$SUDO" ]]; then
        $SUDO install -m 0755 "$TMP_FILE" "$TARGET"
    else
        install -m 0755 "$TMP_FILE" "$TARGET"
    fi

else
    # No standalone binary for this platform - use wheel method
    info "No standalone binary for $PLATFORM, using wheel method ..."
    if [[ -z "$PY_CMD" ]]; then
        die "Python 3.10+ is required for this platform. Install Python first:
  Ubuntu/Debian: sudo apt install python3 python3-venv
  macOS: brew install python3"
    fi

    # Create venv if needed
    if [[ ! -d "$VENV_DIR" ]]; then
        info "Creating Python virtual environment ..."
        "$PY_CMD" -m venv "$VENV_DIR" 2>/dev/null || "$PY_CMD" -m venv --without-pip "$VENV_DIR"
    fi

    # Download wheel from teambot.samai.cc (NOT PyPI)
    info "Looking for compatible wheel from $BASE_URL ..."
    WHL_NAME="$(curl -fsSL "$BASE_URL/" 2>/dev/null | grep -oP 'teambot_ai-[^"]+\.whl' | head -1 || true)"

    if [[ -n "$WHL_NAME" ]]; then
        info "Found wheel: $WHL_NAME"
        if curl -fSL --retry 3 --retry-delay 2 -o "$TMP_FILE" "$BASE_URL/$WHL_NAME"; then
            info "Installing wheel locally (from teambot.samai.cc, NOT PyPI) ..."
            "$VENV_DIR/bin/pip" install --no-deps --no-index "$TMP_FILE" 2>/dev/null || \
            "$VENV_DIR/bin/pip" install "$TMP_FILE" 2>/dev/null || \
            warn "Wheel install failed"
        fi
    fi

    # Create launcher script
    LAUNCHER="${TARGET}"
    info "Creating launcher at $LAUNCHER ..."
    LAUNCHER_DIR="$(dirname "$LAUNCHER")"
    mkdir -p "$LAUNCHER_DIR" 2>/dev/null || true
    cat > "$LAUNCHER" << 'LAUNCHER_EOF'
#!/usr/bin/env bash
exec ~/.teambot/runtime/venv/bin/python -m teambot_ai "$@"
LAUNCHER_EOF
    chmod 755 "$LAUNCHER"
fi

# ---- macOS quarantine notice ---------------------------------------------
if [[ "$PLATFORM_OS" == "darwin" ]]; then
    if command -v xattr >/dev/null 2>&1; then
        xattr -d com.apple.quarantine "$TARGET" 2>/dev/null || true
    fi
    warn "On macOS you may need to allow the binary in System Settings > Privacy & Security."
fi

# ---- PATH hint ------------------------------------------------------------
case ":$PATH:" in
    *":$(dirname "$TARGET"):"*) ;;
    *)
        warn "$(dirname "$TARGET") is not in your PATH."
        warn "Add: export PATH=\"$(dirname "$TARGET"):\$PATH\"" ;;
esac

echo
info "Done! Try it now:"
echo "    teambot              # start teambot"
echo "    teambot web          # web dashboard"
echo "    teambot cli          # CLI interactive mode"
echo
info "Docs: https://teambot.samai.cc   |   Releases: https://teambot.samai.cc/downloads/"
