#!/bin/bash
# Ralph Loop Setup Script
# SmartStack CLI - https://atlashub.ch
#
# This script initializes the Ralph loop with MCP validation
# Usage: setup-ralph-loop.sh "PROMPT" [--max-iterations N] [--completion-promise TEXT]

set -e

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

# Configuration
RALPH_CONFIG_FILE=".ralph/ralph.config.yaml"
RALPH_LOG_DIR=".ralph/logs"
REQUIRED_MCP_SERVERS=("context7" "smartstack")

# Parse arguments
PROMPT=""
MAX_ITERATIONS=0
COMPLETION_PROMISE=""

while [[ $# -gt 0 ]]; do
    case $1 in
        --max-iterations)
            MAX_ITERATIONS="$2"
            shift 2
            ;;
        --completion-promise)
            COMPLETION_PROMISE="$2"
            shift 2
            ;;
        *)
            if [[ -z "$PROMPT" ]]; then
                PROMPT="$1"
            fi
            shift
            ;;
    esac
done

# Functions
log_info() {
    echo -e "${BLUE}[Ralph]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[Ralph]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[Ralph]${NC} $1"
}

log_error() {
    echo -e "${RED}[Ralph]${NC} $1"
}

check_mcp_server() {
    local server_name="$1"
    # Check if MCP server is available via claude mcp list
    if claude mcp list 2>/dev/null | grep -q "$server_name"; then
        return 0
    else
        return 1
    fi
}

validate_mcp_servers() {
    log_info "Validating required MCP servers..."
    local all_ok=true

    for server in "${REQUIRED_MCP_SERVERS[@]}"; do
        if check_mcp_server "$server"; then
            log_success "  ✓ $server available"
        else
            log_error "  ✗ $server NOT FOUND"
            log_warning "    Install with: claude mcp add $server"
            all_ok=false
        fi
    done

    if [[ "$all_ok" == "false" ]]; then
        log_error ""
        log_error "Ralph requires ALL MCP servers to be available."
        log_error "Please install missing servers and try again."
        log_error ""
        log_error "Quick fix: smartstack check-mcp"
        exit 1
    fi

    log_success "All MCP servers validated ✓"
}

ensure_ralph_structure() {
    # Create .ralph directory structure if not exists
    if [[ ! -d ".ralph" ]]; then
        log_info "Creating .ralph directory structure..."
        mkdir -p ".ralph/logs"
        mkdir -p ".ralph/reports"

        # Copy default config if available
        if [[ -f "${CLAUDE_PLUGIN_ROOT}/templates/ralph/ralph.config.yaml" ]]; then
            cp "${CLAUDE_PLUGIN_ROOT}/templates/ralph/ralph.config.yaml" ".ralph/"
        fi

        log_success ".ralph structure created"
    fi

    # Ensure log directory exists
    mkdir -p "$RALPH_LOG_DIR"
}

init_session_log() {
    local session_id=$(date +%Y%m%d_%H%M%S)
    local log_file="$RALPH_LOG_DIR/ralph-session-$session_id.log"

    echo "# Ralph Session Log" > "$log_file"
    echo "# Started: $(date -Iseconds)" >> "$log_file"
    echo "# Prompt: $PROMPT" >> "$log_file"
    echo "# Max Iterations: $MAX_ITERATIONS" >> "$log_file"
    echo "# Completion Promise: $COMPLETION_PROMISE" >> "$log_file"
    echo "" >> "$log_file"

    export RALPH_SESSION_LOG="$log_file"
    export RALPH_SESSION_ID="$session_id"

    log_info "Session log: $log_file"
}

# Main execution
echo ""
echo -e "${BLUE}╔══════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║${NC}       ${GREEN}Ralph Weegund${NC} - SmartStack        ${BLUE}║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════╝${NC}"
echo ""

# Validate prompt
if [[ -z "$PROMPT" ]]; then
    log_error "No prompt provided!"
    log_info "Usage: /ralph-loop \"Your feature description\""
    exit 1
fi

# Run validations
validate_mcp_servers
ensure_ralph_structure
init_session_log

# Display configuration
echo ""
log_info "Configuration:"
echo "  • Prompt: $PROMPT"
[[ $MAX_ITERATIONS -gt 0 ]] && echo "  • Max iterations: $MAX_ITERATIONS"
[[ -n "$COMPLETION_PROMISE" ]] && echo "  • Completion promise: $COMPLETION_PROMISE"
echo ""

log_success "Ralph is ready. Starting iteration loop..."
echo ""

# Export for Claude to use
export RALPH_PROMPT="$PROMPT"
export RALPH_MAX_ITERATIONS="$MAX_ITERATIONS"
export RALPH_COMPLETION_PROMISE="$COMPLETION_PROMISE"
export RALPH_STARTED="true"

# The actual loop behavior is handled by Claude Code
# This script just sets up the environment
exit 0
