#!/bin/bash
#
# Lingti Bot Installer
# Usage: curl -fsSL https://files.lingti.com/install-bot.sh | bash
#

set -e

BASE_URL="https://files.lingti.com"
MANIFEST_URL="${BASE_URL}/lsbot-version.json"
BINARY_NAME="lsbot"
INSTALL_DIR="/usr/local/bin"

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

info()  { echo -e "${GREEN}[INFO]${NC} $1"; }
warn()  { echo -e "${YELLOW}[WARN]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }

detect_os() {
    case "$(uname -s)" in
        Darwin) echo "darwin" ;;
        Linux)  echo "linux" ;;
        *)      error "Unsupported OS: $(uname -s)" ;;
    esac
}

detect_arch() {
    case "$(uname -m)" in
        x86_64|amd64)   echo "amd64" ;;
        arm64|aarch64)  echo "arm64" ;;
        *)              error "Unsupported architecture: $(uname -m)" ;;
    esac
}

check_permissions() {
    if [ "$EUID" -eq 0 ]; then
        SUDO=""
    elif command -v sudo &>/dev/null; then
        SUDO="sudo"
    else
        error "Root privileges required. Run as root or install sudo."
    fi
}

download_stdout() {
    if command -v curl &>/dev/null; then
        curl -fsSL "$1"
    elif command -v wget &>/dev/null; then
        wget -q "$1" -O -
    else
        error "Neither curl nor wget found. Please install one of them."
    fi
}

download() {
    if command -v curl &>/dev/null; then
        curl -fsSL "$1" -o "$2"
    elif command -v wget &>/dev/null; then
        wget -q "$1" -O "$2"
    else
        error "Neither curl nor wget found. Please install one of them."
    fi
}

fetch_bot_info() {
    local os="$1" arch="$2"

    info "Fetching latest lsbot version from manifest..."
    local manifest
    manifest=$(download_stdout "$MANIFEST_URL") || error "Failed to fetch manifest: $MANIFEST_URL"

    if command -v python3 &>/dev/null; then
        BOT_VERSION=$(echo "$manifest" | python3 -c "import sys,json; print(json.load(sys.stdin)['version'])")
    else
        BOT_VERSION=$(echo "$manifest" | grep '"version"' | head -1 | sed 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/')
    fi
    [ -n "$BOT_VERSION" ] || error "Could not parse version from manifest"

    local target="${BINARY_NAME}-${BOT_VERSION}-${os}-${arch}"

    if command -v python3 &>/dev/null; then
        BOT_URL=$(echo "$manifest" | python3 -c "
import sys, json
d = json.load(sys.stdin)
target = '${target}'
for f in d.get('files', []):
    if f['name'] == target:
        print(f['url'])
        break
")
    else
        BOT_URL=$(echo "$manifest" | grep -A3 "\"$target\"" | grep '"url"' | head -1 | sed 's/.*"url"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/')
    fi
    [ -n "$BOT_URL" ] || error "No manifest entry for platform: $target"
}

main() {
    local os arch
    os=$(detect_os)
    arch=$(detect_arch)

    check_permissions
    fetch_bot_info "$os" "$arch"

    echo ""
    echo "================================"
    echo "  Lingti Bot Installer v${BOT_VERSION}"
    echo "================================"
    echo ""

    info "Platform: ${os}/${arch}"
    info "Downloading ${BINARY_NAME} v${BOT_VERSION}..."

    local tmpdir
    tmpdir=$(mktemp -d)
    trap "rm -rf $tmpdir" EXIT

    local tmpfile="${tmpdir}/${BINARY_NAME}"
    download "$BOT_URL" "$tmpfile"
    chmod +x "$tmpfile"

    if ! "$tmpfile" version &>/dev/null; then
        error "Downloaded binary appears to be invalid"
    fi

    info "Installing to ${INSTALL_DIR}/${BINARY_NAME}..."
    $SUDO mkdir -p "$INSTALL_DIR"
    $SUDO mv "$tmpfile" "${INSTALL_DIR}/${BINARY_NAME}"

    if ! command -v "$BINARY_NAME" &>/dev/null; then
        warn "${INSTALL_DIR} may not be in your PATH"
        warn "Add it with: export PATH=\"${INSTALL_DIR}:\$PATH\""
    fi

    echo ""
    info "Lingti Bot installed successfully!"
    echo ""
    "${INSTALL_DIR}/${BINARY_NAME}" version
    echo ""
    echo "========================================"
    echo "  Installation complete!"
    echo "========================================"
    echo ""

    "${INSTALL_DIR}/${BINARY_NAME}" quickstart
}

main "$@"
