#!/bin/bash
# Bluera Knowledge Plugin - Readiness Check
# Runs on: every SessionStart - must be FAST (<5s)
#
# This script only CHECKS if setup is complete.
# Auto-setup runs async via auto-setup.sh on SessionStart.

# Drain stdin so the pipe doesn't hang
cat > /dev/null 2>&1 || true

PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(dirname "$(dirname "$0")")}"

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# Debug logging - writes JSON to same log file as bootstrap.ts
# Uses PROJECT_ROOT if available (set by Claude Code), else current dir
LOG_DIR="${PROJECT_ROOT:-.}/.bluera/bluera-knowledge/logs"
LOG_FILE="$LOG_DIR/app.log"

log_debug() {
    local msg="$1"
    mkdir -p "$LOG_DIR" 2>/dev/null || true
    # macOS date doesn't support %3N, fallback to seconds-only
    local timestamp
    timestamp=$(date -u +"%Y-%m-%dT%H:%M:%S.000Z" 2>/dev/null || date -u +"%Y-%m-%dT%H:%M:%SZ")
    echo "{\"time\":\"$timestamp\",\"level\":\"debug\",\"module\":\"check-ready.sh\",\"msg\":\"$msg\"}" >> "$LOG_FILE" 2>/dev/null || true
}

log_debug "Check-ready starting, PLUGIN_ROOT=$PLUGIN_ROOT, PROJECT_ROOT=${PROJECT_ROOT:-unset}"

missing_setup=false

# Fast check: node_modules exists?
log_debug "Checking node_modules at $PLUGIN_ROOT/node_modules"
if [ ! -d "$PLUGIN_ROOT/node_modules" ]; then
    log_debug "node_modules missing"
    echo -e "${YELLOW}[bluera-knowledge] ⚠️  Dependencies not installed. Setup running in background...${NC}"
    missing_setup=true
else
    log_debug "node_modules exists"
fi

# Fast check: MCP wrapper script installed?
# The wrapper is installed to ~/.local/bin/bluera-knowledge-mcp by setup.sh
# Without it, MCP server can't start (workaround for CLAUDE_PLUGIN_ROOT bug #9427)
WRAPPER_PATH="$HOME/.local/bin/bluera-knowledge-mcp"
log_debug "Checking MCP wrapper at $WRAPPER_PATH"
if [ ! -f "$WRAPPER_PATH" ]; then
    log_debug "MCP wrapper missing"
    echo -e "${YELLOW}[bluera-knowledge] ⚠️  MCP wrapper not installed. Setup running in background...${NC}"
    missing_setup=true
else
    log_debug "MCP wrapper exists"
fi

# Fast check: build tools available?
# Native modules require make/gcc - this is a BLOCKING prerequisite
# Note: SessionStart stderr doesn't display (Bug #12653), so write to /dev/tty
log_debug "Checking build tools (make)"
if ! command -v make &>/dev/null; then
    log_debug "Build tools (make) not found - blocking error"
    ERROR_MSG="[bluera-knowledge] ERROR: Build tools (make) not found - required for native modules.

Install build tools, then restart Claude Code:
  Debian/Ubuntu: sudo apt install build-essential
  Fedora/RHEL:   sudo dnf groupinstall 'Development Tools'
  macOS:         xcode-select --install"

    # Write to /dev/tty for immediate visibility (workaround for Bug #12653)
    if [ -w /dev/tty ]; then
        printf "\033[1;31m%s\033[0m\n" "$ERROR_MSG" > /dev/tty 2>/dev/null || true
    fi
    # Also write to stderr in case bug is fixed
    echo "$ERROR_MSG" >&2
    exit 2
fi
log_debug "Build tools (make) available"

# Fast check: Playwright Chromium installed?
PLAYWRIGHT_BROWSERS_PATH="${PLAYWRIGHT_BROWSERS_PATH:-$HOME/.cache/ms-playwright}"
log_debug "Checking playwright at $PLAYWRIGHT_BROWSERS_PATH/chromium-*"
if ! ls "$PLAYWRIGHT_BROWSERS_PATH"/chromium-* 1>/dev/null 2>&1; then
    log_debug "Playwright chromium missing"
    if [ "$missing_setup" = false ]; then
        echo -e "${YELLOW}[bluera-knowledge] ⚠️  Playwright browser not installed. Setup running in background...${NC}"
    fi
    missing_setup=true
else
    log_debug "Playwright chromium exists"
fi

# If setup is complete, show ready message with store catalog
if [ "$missing_setup" = false ]; then
    log_debug "All checks passed, building ready message"
    store_hint=""
    if command -v python3 &>/dev/null; then
        # Use shared helper to get store names (compact, fast)
        store_hint=$(python3 -c "
import sys, os
sys.path.insert(0, os.path.join(os.environ.get('CLAUDE_PLUGIN_ROOT', '.'), 'hooks', 'lib'))
from store_summary import load_stores, format_store_names
stores = load_stores()
if stores:
    print(f'{len(stores)} stores: {format_store_names(stores, cap=5)}')
" 2>/dev/null || true)
    fi
    if [ -n "$store_hint" ]; then
        log_debug "Store catalog: $store_hint"
        echo -e "${GREEN}[bluera-knowledge] Ready ✓ — ${store_hint}${NC}"
    else
        log_debug "No stores or python unavailable"
        echo -e "${GREEN}[bluera-knowledge] Ready ✓${NC}"
    fi
fi

log_debug "Check-ready complete, missing_setup=$missing_setup"

# Always exit 0 to not block the session
exit 0
