#!/usr/bin/env bash
#
# claude-mpm-hooks - Launch the centralized hook service
#
# This script ensures proper environment setup before launching the hook service

set -e

# Find the project root (where this script is located)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

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

# Function to print colored output
print_status() {
    echo -e "${GREEN}[HOOKS]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1" >&2
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

# Check if virtual environment exists
VENV_PATH="$PROJECT_ROOT/venv"
if [ ! -d "$VENV_PATH" ]; then
    print_error "Virtual environment not found at $VENV_PATH"
    print_status "Please run: python -m venv venv"
    exit 1
fi

# Activate virtual environment
print_status "Activating virtual environment..."
source "$VENV_PATH/bin/activate"

# Set up Python path
export PYTHONPATH="$PROJECT_ROOT:$PYTHONPATH"

# Check if Flask is installed
if ! python -c "import flask" 2>/dev/null; then
    print_error "Flask not installed. Installing dependencies..."
    pip install -e "$PROJECT_ROOT"
fi

# Parse command line arguments
PORT=5001
LOG_LEVEL="INFO"

while [[ $# -gt 0 ]]; do
    case $1 in
        --port)
            PORT="$2"
            shift 2
            ;;
        --log-level)
            LOG_LEVEL="$2"
            shift 2
            ;;
        --help)
            echo "Usage: $0 [options]"
            echo ""
            echo "Options:"
            echo "  --port PORT           Port to run hook service on (default: 5001)"
            echo "  --log-level LEVEL     Logging level (default: INFO)"
            echo "  --help                Show this help message"
            exit 0
            ;;
        *)
            print_error "Unknown option: $1"
            echo "Use --help for usage information"
            exit 1
            ;;
    esac
done

# Create logs directory if it doesn't exist
LOGS_DIR="$PROJECT_ROOT/logs"
mkdir -p "$LOGS_DIR"

# Set up environment variables
export CLAUDE_MPM_ROOT="$PROJECT_ROOT"
export CLAUDE_MPM_HOOKS_PORT="$PORT"
export CLAUDE_MPM_LOG_LEVEL="$LOG_LEVEL"

# Log file path
LOG_FILE="$LOGS_DIR/hooks_$(date +%Y%m%d_%H%M%S).log"

print_status "Starting Claude MPM Hook Service..."
print_status "Port: $PORT"
print_status "Log Level: $LOG_LEVEL"
print_status "Log File: $LOG_FILE"
print_status "Project Root: $PROJECT_ROOT"

# Launch the hook service
exec python -m src.services.hook_service \
    --port "$PORT" \
    --log-level "$LOG_LEVEL" \
    2>&1 | tee "$LOG_FILE"