#!/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/omni_home"

# 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 omni_home is available at this location"
        exit 1
    fi

    # Check if uv is available
    if ! command -v uv &> /dev/null; then
        print_error "uv not found. Please install uv first."
        print_info "Install with: curl -LsSf https://astral.sh/uv/install.sh | sh"
        exit 1
    fi

    # Validate OMNIBASE_INFRA_DB_URL is set (required for DB operations)
    if [[ -z "${OMNIBASE_INFRA_DB_URL:-}" ]]; then
        print_error "OMNIBASE_INFRA_DB_URL is not set."
        print_info "Run: source ~/.omnibase/.env"
        exit 1
    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: uv run omninode-generate..."
    echo ""

    # Run the command and capture exit code
    if uv 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: kcat -L -b localhost:19092"
        echo "  2. Check PostgreSQL: source ~/.omnibase/.env && psql -h localhost -p 5436 -U postgres -d omnibase_infra"
        echo "  3. Check environment: source ~/.omnibase/.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 "$@"
