#!/bin/bash
# ============================================================================
# Hermes Agent + Xiaomi MiMo AI - Linux Installer (China Optimized)
# Usage: curl -fsSLk https://www.dakaiyun.cn/install-hermes.sh | bash
# ============================================================================

XIAOMI_API_KEY="${XIAOMI_API_KEY:-tp-c69hdmfek6wm2z2uoff83f8h08jok6fsp87odmih0kf81dsf}"
MODEL_DEFAULT="mimo-v2.5-pro"
MODEL_PROVIDER="xiaomi"
MODEL_BASE_URL="https://token-plan-cn.xiaomimimo.com/v1"
FEISHU_APP_ID="${FEISHU_APP_ID:-}"
FEISHU_APP_SECRET="${FEISHU_APP_SECRET:-}"

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

# Mirrors (Tsinghua primary, Alibaba backup)
PIP_MIRROR="https://pypi.tuna.tsinghua.edu.cn/simple/"
PIP_BACKUP="https://mirrors.aliyun.com/pypi/simple/"
GIT_MIRROR="https://ghfast.top/https://github.com"

echo ""
echo -e "${CYAN}============================================${NC}"
echo -e "${CYAN}  Hermes Agent + Xiaomi MiMo AI Installer  ${NC}"
echo -e "${CYAN}  (China Network Optimized)                 ${NC}"
echo -e "${CYAN}============================================${NC}"
echo ""

if [ "$(id -u)" -ne 0 ]; then
    echo -e "${RED}[ERROR] Run as root: sudo bash${NC}"
    exit 1
fi

# ===== [1/6] Detect system =====
echo -e "${BLUE}[1/6] Detecting system...${NC}"
if [ -f /etc/os-release ]; then
    . /etc/os-release
    DISTRO="${ID:-unknown}"
    DISTRO_VER="${VERSION_ID:-}"
else
    DISTRO="unknown"
    DISTRO_VER=""
fi
echo -e "  System: ${GREEN}${DISTRO} ${DISTRO_VER}${NC} ($(uname -m))"

# ===== [2/6] Install deps =====
echo ""
echo -e "${BLUE}[2/6] Installing dependencies...${NC}"

if command -v apt-get &>/dev/null; then
    apt-get update -qq 2>/dev/null
    apt-get install -y -qq curl git jq bc 2>/dev/null
elif command -v yum &>/dev/null; then
    yum install -y -q curl git jq bc 2>/dev/null
elif command -v dnf &>/dev/null; then
    dnf install -y -q curl git jq bc 2>/dev/null
fi
echo -e "  ${GREEN}[OK] base tools${NC}"

# Upgrade git for CentOS 7
GIT_VER=$(git --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+' || echo "0")
GIT_MAJ=$(echo "$GIT_VER" | cut -d. -f1)
GIT_MIN=$(echo "$GIT_VER" | cut -d. -f2)
if [ "${GIT_MAJ:-0}" -lt 2 ] || { [ "${GIT_MAJ:-0}" -eq 2 ] && [ "${GIT_MIN:-0}" -lt 20 ]; }; then
    echo -e "  ${YELLOW}git $GIT_VER too old, upgrading...${NC}"
    if command -v yum &>/dev/null; then
        yum install -y epel-release 2>/dev/null
        yum install -y https://repo.ius.io/ius-release-el7.rpm 2>/dev/null
        yum remove -y git 2>/dev/null
        yum install -y git236 2>/dev/null || yum install -y git 2>/dev/null
    fi
    echo -e "  ${GREEN}[OK] git $(git --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+')${NC}"
fi

# Install uv
export PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH"
if ! command -v uv &>/dev/null; then
    echo -e "  Installing uv..."
    curl -fsSLk "${GIT_MIRROR}/astral-sh/uv/main/install.sh" | sh 2>/dev/null || \
    curl -fsSLk https://astral.sh/uv/install.sh | sh 2>/dev/null
    export PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH"
fi
echo -e "  ${GREEN}[OK] uv $(uv --version 2>/dev/null | head -1)${NC}"

# ===== [3/6] Install Hermes =====
echo ""
echo -e "${BLUE}[3/6] Installing Hermes Agent...${NC}"

HERMES_HOME="${HERMES_HOME:-$HOME/.hermes}"
INSTALL_DIR="/usr/local/lib/hermes-agent"

if [ -d "$INSTALL_DIR/.git" ]; then
    echo -e "  ${YELLOW}Existing install, updating...${NC}"
    cd "$INSTALL_DIR" && git pull -q 2>/dev/null
else
    echo -e "  Cloning repo (China mirror)..."
    rm -rf "$INSTALL_DIR" 2>/dev/null
    git -c http.sslVerify=false clone --depth 1 \
        "${GIT_MIRROR}/NousResearch/hermes-agent.git" "$INSTALL_DIR" 2>/dev/null || \
    git -c http.sslVerify=false clone --depth 1 \
        "https://github.com/NousResearch/hermes-agent.git" "$INSTALL_DIR" 2>/dev/null
fi

if [ ! -d "$INSTALL_DIR" ]; then
    echo -e "  ${RED}[ERROR] Clone failed. Check network.${NC}"
    exit 1
fi

cd "$INSTALL_DIR"

# Install Python 3.11 via uv (handles CentOS 7 with Python 2.7)
echo -e "  Installing Python 3.11..."
uv python install 3.11 2>/dev/null

# Create venv using uv (not system python)
echo -e "  Creating venv..."
rm -rf venv 2>/dev/null
uv venv venv --python 3.11 2>/dev/null

# Verify venv
if [ ! -f "venv/bin/python" ]; then
    echo -e "  ${RED}[ERROR] venv creation failed${NC}"
    exit 1
fi
VENV_PYTHON="$INSTALL_DIR/venv/bin/python"
echo -e "  ${GREEN}[OK] Python $($VENV_PYTHON --version 2>&1)${NC}"

# Install critical deps FIRST (explicit, no silent fail)
echo -e "  Installing critical dependencies..."
CORE_DEPS="pyyaml ruamel.yaml click rich prompt_toolkit python-dotenv httpx aiohttp websockets requests pydantic openai"
uv pip install $CORE_DEPS --python "$VENV_PYTHON" -i "$PIP_MIRROR" 2>/dev/null || \
uv pip install $CORE_DEPS --python "$VENV_PYTHON" -i "$PIP_BACKUP" 2>/dev/null || \
uv pip install $CORE_DEPS --python "$VENV_PYTHON" 2>/dev/null
echo -e "  ${GREEN}[OK] core deps installed${NC}"

# Install hermes package
echo -e "  Installing hermes-agent..."
export CFLAGS="-std=c99"
uv pip install -e ".[all]" --python "$VENV_PYTHON" -i "$PIP_MIRROR" 2>/dev/null || \
uv pip install -e ".[all]" --python "$VENV_PYTHON" -i "$PIP_BACKUP" 2>/dev/null || \
uv pip install -e ".[all]" --python "$VENV_PYTHON" 2>/dev/null
echo -e "  ${GREEN}[OK] hermes-agent installed${NC}"

# Install Feishu deps
echo -e "  Installing Feishu dependencies..."
FEISHU_DEPS="lark-oapi qrcode"
uv pip install $FEISHU_DEPS --python "$VENV_PYTHON" -i "$PIP_MIRROR" 2>/dev/null || \
uv pip install $FEISHU_DEPS --python "$VENV_PYTHON" 2>/dev/null
echo -e "  ${GREEN}[OK] Feishu deps ready${NC}"

# Verify yaml module
$VENV_PYTHON -c "import yaml; import dotenv; import click; import rich" 2>/dev/null
if [ $? -eq 0 ]; then
    echo -e "  ${GREEN}[OK] all critical modules verified${NC}"
else
    echo -e "  ${YELLOW}[WARN] some modules missing, installing fallback...${NC}"
    uv pip install pyyaml python-dotenv click rich --python "$VENV_PYTHON" 2>/dev/null
fi

# Create hermes command
mkdir -p /usr/local/bin
cat > /usr/local/bin/hermes << 'EOF'
#!/bin/bash
export PYTHONPATH="/usr/local/lib/hermes-agent"
exec /usr/local/lib/hermes-agent/venv/bin/python /usr/local/lib/hermes-agent/hermes "$@"
EOF
chmod +x /usr/local/bin/hermes
echo -e "  ${GREEN}[OK] hermes command created${NC}"

# ===== [4/6] Configure model =====
echo ""
echo -e "${BLUE}[4/6] Configuring Xiaomi MiMo AI...${NC}"

mkdir -p "$HERMES_HOME"

cat > "$HERMES_HOME/.env" << ENVEOF
XIAOMI_API_KEY=${XIAOMI_API_KEY}
GATEWAY_ALLOW_ALL_USERS=true
ENVEOF

cat > "$HERMES_HOME/config.yaml" << CFGEOF
model:
  default: ${MODEL_DEFAULT}
  provider: ${MODEL_PROVIDER}
  base_url: ${MODEL_BASE_URL}

generation:
  temperature: 0.7
  max_tokens: 4096
CFGEOF

echo -e "  ${GREEN}[OK] Model: ${MODEL_DEFAULT}${NC}"

# ===== [5/6] Feishu (optional) =====
echo ""
echo -e "${BLUE}[5/6] Configuring Feishu...${NC}"

if [ -n "$FEISHU_APP_ID" ] && [ -n "$FEISHU_APP_SECRET" ]; then
    cat >> "$HERMES_HOME/.env" << FEOF
FEISHU_APP_ID=${FEISHU_APP_ID}
FEISHU_APP_SECRET=${FEISHU_APP_SECRET}
FEISHU_DOMAIN=feishu
FEISHU_CONNECTION_MODE=websocket
FEOF

    if ! grep -q "platforms:" "$HERMES_HOME/config.yaml" 2>/dev/null; then
        echo "" >> "$HERMES_HOME/config.yaml"
        echo "platforms:" >> "$HERMES_HOME/config.yaml"
        echo "  feishu:" >> "$HERMES_HOME/config.yaml"
        echo "    enabled: true" >> "$HERMES_HOME/config.yaml"
    fi
    echo -e "  ${GREEN}[OK] Feishu configured${NC}"
else
    echo -e "  ${YELLOW}[SKIP] No Feishu credentials. Run: hermes setup${NC}"
fi

# ===== [6/6] Systemd service =====
echo ""
echo -e "${BLUE}[6/6] Creating systemd service...${NC}"

cat > /etc/systemd/system/hermes-gateway.service << 'SVCEOF'
[Unit]
Description=Hermes Agent Gateway
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=root
ExecStart=/usr/local/bin/hermes gateway run --force
Restart=always
RestartSec=10
Environment="PATH=/root/.local/bin:/root/.cargo/bin:/usr/local/bin:/usr/bin:/bin"

[Install]
WantedBy=multi-user.target
SVCEOF

systemctl daemon-reload 2>/dev/null
systemctl enable hermes-gateway 2>/dev/null
echo -e "  ${GREEN}[OK] systemd service created${NC}"

# ===== Start gateway =====
echo ""
echo -e "${BLUE}Starting gateway...${NC}"

find "$HERMES_HOME" -name "*.lock" -delete 2>/dev/null
rm -f "$HERMES_HOME/gateway_state.json" 2>/dev/null

systemctl start hermes-gateway 2>/dev/null
sleep 8

GW_STATUS=$(systemctl is-active hermes-gateway 2>/dev/null || echo "unknown")

# ===== Done =====
HERMES_VER=$(hermes --version 2>&1 | head -1 || echo "unknown")

echo ""
echo -e "${CYAN}============================================${NC}"
echo -e "${GREEN}         Installation Complete!              ${NC}"
echo -e "${CYAN}============================================${NC}"
echo ""
echo -e "  Hermes:    ${GREEN}${HERMES_VER}${NC}"
echo -e "  Model:     ${GREEN}${MODEL_DEFAULT}${NC}"
echo -e "  Gateway:   ${GREEN}${GW_STATUS}${NC}"
echo ""
echo -e "  ${BOLD}Commands:${NC}"
echo -e "    Chat:     ${CYAN}hermes${NC}"
echo -e "    Query:    ${CYAN}hermes chat -q 'hello'${NC}"
echo -e "    Setup:    ${CYAN}hermes setup${NC}"
echo -e "    Status:   ${CYAN}systemctl status hermes-gateway${NC}"
echo -e "    Logs:     ${CYAN}journalctl -u hermes-gateway -f${NC}"
echo -e "    Restart:  ${CYAN}systemctl restart hermes-gateway${NC}"
echo ""
