#!/usr/bin/env bash
#
# ONEX Node Generator - Claude Code Skill
#
# Wrapper for omninode-generate CLI that handles:
# - Automatic repository navigation
# - Environment setup
# - Progress tracking
# - Error handling
#
# Usage:
#   ${CLAUDE_PLUGIN_ROOT}/skills/generate-node/generate "PROMPT" [OPTIONS]
#
# Examples:
#   ${CLAUDE_PLUGIN_ROOT}/skills/generate-node/generate "Create PostgreSQL CRUD Effect"
#   ${CLAUDE_PLUGIN_ROOT}/skills/generate-node/generate "Create ML Orchestrator" --interactive
#

set -euo pipefail

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

# Repository path
REPO_PATH="/Volumes/PRO-G40/Code/omninode_bridge"

# Function to print colored messages
print_error() {
    echo -e "${RED}❌ Error: $1${NC}" >&2
}

print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

# Function to check prerequisites
check_prerequisites() {
    # Check if repository exists
    if [[ ! -d "$REPO_PATH" ]]; then
        print_error "Repository not found: $REPO_PATH"
        print_info "Please ensure omninode_bridge is cloned at this location"
        exit 1
    fi

    # Check if poetry is available
    if ! command -v poetry &> /dev/null; then
        print_error "Poetry not found. Please install poetry first."
        print_info "Install with: curl -sSL https://install.python-poetry.org | python3 -"
        exit 1
    fi

    # Check if .env file exists
    if [[ ! -f "$REPO_PATH/.env" ]]; then
        print_warning ".env file not found in $REPO_PATH"
        print_info "Some features may not work without proper configuration"
        print_info "Copy .env.example to .env and configure it"
    fi
}

# Function to validate prompt
validate_prompt() {
    local prompt="$1"

    if [[ -z "$prompt" ]]; then
        print_error "Prompt cannot be empty"
        echo ""
        echo "Usage: $0 \"PROMPT\" [OPTIONS]"
        echo ""
        echo "Examples:"
        echo "  $0 \"Create PostgreSQL CRUD Effect\""
        echo "  $0 \"Create ML inference Orchestrator\" --interactive"
        echo "  $0 \"Create metrics Reducer\" --output-dir ./my_nodes"
        echo ""
        exit 1
    fi

    # Check prompt length (max 10KB)
    if [[ ${#prompt} -gt 10000 ]]; then
        print_error "Prompt too long (${#prompt} chars). Maximum 10000 characters allowed."
        exit 1
    fi
}

# Main execution
main() {
    # Check if no arguments provided
    if [[ $# -eq 0 ]]; then
        print_error "No arguments provided"
        echo ""
        echo "Usage: $0 \"PROMPT\" [OPTIONS]"
        echo ""
        echo "Options:"
        echo "  --output-dir TEXT               Output directory (default: ./generated_nodes)"
        echo "  --node-type [effect|orchestrator|reducer|compute]"
        echo "  --interactive                   Enable interactive checkpoints"
        echo "  --enable-intelligence           Use RAG intelligence (default: enabled)"
        echo "  --disable-intelligence          Disable RAG intelligence"
        echo "  --enable-quorum                 Use AI quorum validation"
        echo "  --timeout INTEGER               Timeout in seconds (default: 300)"
        echo ""
        echo "Examples:"
        echo "  $0 \"Create PostgreSQL CRUD Effect\""
        echo "  $0 \"Create ML Orchestrator\" --interactive"
        echo "  $0 \"Create metrics Reducer\" --node-type reducer"
        echo ""
        exit 1
    fi

    print_info "ONEX Node Generator - Starting..."
    echo ""

    # Check prerequisites
    check_prerequisites

    # Extract prompt (first argument)
    local prompt="$1"
    shift

    # Validate prompt
    validate_prompt "$prompt"

    # Change to repository directory
    print_info "Navigating to: $REPO_PATH"
    cd "$REPO_PATH" || {
        print_error "Failed to navigate to repository"
        exit 1
    }

    # Show current configuration
    print_info "Repository: $(basename "$REPO_PATH")"
    print_info "Prompt: \"$prompt\""
    if [[ $# -gt 0 ]]; then
        print_info "Options: $*"
    fi
    echo ""

    # Execute omninode-generate
    print_info "Executing: poetry run omninode-generate..."
    echo ""

    # Run the command and capture exit code
    if poetry run omninode-generate "$prompt" "$@"; then
        echo ""
        print_success "Node generation completed successfully!"
        exit 0
    else
        local exit_code=$?
        echo ""
        print_error "Node generation failed with exit code: $exit_code"
        echo ""
        print_info "Troubleshooting:"
        echo "  1. Check Kafka connection: curl http://192.168.86.200:8080"
        echo "  2. Check PostgreSQL: psql -h 192.168.86.200 -p 5436 -U postgres -d omninode_bridge"
        echo "  3. Check environment: source $REPO_PATH/.env && env | grep -E '(POSTGRES|KAFKA|OPENAI)'"
        echo "  4. Check logs for correlation ID and search in Kafka/PostgreSQL"
        echo ""
        exit "$exit_code"
    fi
}

# Execute main with all arguments
main "$@"
