#!/usr/bin/env bash
# ============================================================================
# EasyClaw Fresh Install Test Script
#
# Run on a clean Ubuntu 22.04+ VM to validate the full install flow:
#   curl -fsSL https://easyclaw.help/install.sh | bash
#
# Usage:
#   chmod +x test_fresh_install.sh
#   sudo ./test_fresh_install.sh
#
# This script does NOT launch the TUI — it validates all prerequisites and
# the install pipeline up to the point where the TUI would start.
# ============================================================================
set -euo pipefail

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

PASS=0
FAIL=0
TOTAL=0

pass() { PASS=$((PASS + 1)); TOTAL=$((TOTAL + 1)); echo -e "${GREEN}  PASS${NC} $1"; }
fail() { FAIL=$((FAIL + 1)); TOTAL=$((TOTAL + 1)); echo -e "${RED}  FAIL${NC} $1"; }
skip() { TOTAL=$((TOTAL + 1)); echo -e "${YELLOW}  SKIP${NC} $1"; }

echo "============================================"
echo "  EasyClaw Fresh Install Test"
echo "============================================"
echo ""

# ── 1. Check we're on Linux ──────────────────────────────────────────────────
echo "--- Environment ---"
if [ "$(uname -s)" = "Linux" ]; then
    pass "Running on Linux"
else
    fail "Not running on Linux ($(uname -s))"
    echo "This test must run on a Linux system."
    exit 1
fi

# ── 2. Check root ────────────────────────────────────────────────────────────
if [ "$(id -u)" -eq 0 ]; then
    pass "Running as root"
else
    fail "Not running as root (run with sudo)"
    exit 1
fi

# ── 3. Check OS ──────────────────────────────────────────────────────────────
if [ -f /etc/os-release ]; then
    . /etc/os-release
    pass "OS detected: $PRETTY_NAME"
else
    fail "/etc/os-release not found"
fi

# ── 4. Check apt-get ─────────────────────────────────────────────────────────
if command -v apt-get >/dev/null 2>&1; then
    pass "apt-get available"
else
    fail "apt-get not found (Ubuntu/Debian required)"
fi

# ── 5. Check curl ────────────────────────────────────────────────────────────
if command -v curl >/dev/null 2>&1; then
    pass "curl available"
else
    skip "curl not found — installing..."
    apt-get install -y -qq curl && pass "curl installed" || fail "Failed to install curl"
fi

# ── 6. Test bootstrap.sh is accessible ────────────────────────────────────────
echo ""
echo "--- Network Checks ---"
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" https://easyclaw.help/install.sh)
if [ "$HTTP_CODE" = "200" ]; then
    pass "bootstrap.sh accessible (HTTP $HTTP_CODE)"
else
    fail "bootstrap.sh returned HTTP $HTTP_CODE"
fi

# ── 7. Test npm tarballs are accessible ──────────────────────────────────────
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" https://easyclaw.help/packages/openclaw-cli-0.1.0.tgz)
if [ "$HTTP_CODE" = "200" ]; then
    pass "openclaw-cli tarball accessible"
else
    fail "openclaw-cli tarball returned HTTP $HTTP_CODE"
fi

HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" https://easyclaw.help/packages/openclaw-mcp-tools-0.1.0.tgz)
if [ "$HTTP_CODE" = "200" ]; then
    pass "openclaw-mcp-tools tarball accessible"
else
    fail "openclaw-mcp-tools tarball returned HTTP $HTTP_CODE"
fi

# ── 8. Test PyPI package is available ────────────────────────────────────────
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" https://pypi.org/pypi/easyclaw-installer/json)
if [ "$HTTP_CODE" = "200" ]; then
    pass "easyclaw-installer on PyPI"
else
    fail "PyPI check returned HTTP $HTTP_CODE"
fi

# ── 9. Test MCP server health ────────────────────────────────────────────────
MCP_HEALTH=$(curl -s -o /dev/null -w "%{http_code}" https://mcp.easyclaw.help/health)
if [ "$MCP_HEALTH" = "200" ]; then
    pass "MCP server healthy"
else
    fail "MCP server returned HTTP $MCP_HEALTH"
fi

# ── 10. Run the actual bootstrap (non-interactive) ──────────────────────────
echo ""
echo "--- Bootstrap Install ---"

# Clean up any previous install
rm -rf /opt/easyclaw-installer
rm -f /usr/local/bin/easyclaw-install

# Download and run bootstrap (stop before TUI launch by modifying the exec)
BOOTSTRAP=$(curl -fsSL https://easyclaw.help/install.sh)
# Replace the final 'exec' with an echo so we don't launch the TUI
MODIFIED_BOOTSTRAP=$(echo "$BOOTSTRAP" | sed 's|^exec .*|echo "BOOTSTRAP_COMPLETE"|')
echo "$MODIFIED_BOOTSTRAP" | bash -s -- 2>&1 | tail -5

if [ $? -eq 0 ]; then
    pass "Bootstrap script completed"
else
    fail "Bootstrap script failed"
fi

# ── 11. Verify installation artifacts ────────────────────────────────────────
echo ""
echo "--- Verification ---"

if [ -d "/opt/easyclaw-installer/.venv" ]; then
    pass "Venv exists at /opt/easyclaw-installer/.venv/"
else
    fail "Venv not found"
fi

if [ -f "/usr/local/bin/easyclaw-install" ]; then
    pass "easyclaw-install symlink exists"
else
    fail "easyclaw-install symlink not found"
fi

# Check package is installed
if /opt/easyclaw-installer/.venv/bin/pip show easyclaw-installer >/dev/null 2>&1; then
    VERSION=$(/opt/easyclaw-installer/.venv/bin/pip show easyclaw-installer | grep "^Version:" | awk '{print $2}')
    pass "easyclaw-installer v$VERSION installed"
else
    fail "easyclaw-installer not installed in venv"
fi

# Check entry point works
if /opt/easyclaw-installer/.venv/bin/python -m easyclaw_installer --help >/dev/null 2>&1; then
    pass "easyclaw-install --help works"
else
    fail "easyclaw-install --help failed"
fi

# ── Summary ──────────────────────────────────────────────────────────────────
echo ""
echo "============================================"
if [ "$FAIL" -eq 0 ]; then
    echo -e "${GREEN}  ALL $TOTAL TESTS PASSED${NC}"
else
    echo -e "${RED}  $FAIL/$TOTAL TESTS FAILED${NC}"
fi
echo "============================================"

exit "$FAIL"
