#!/bin/bash

# Simple Text Storage Service Setup Script
# This script provides easy setup and management commands
# NOTE: Simplified from advanced cognitive memory system to basic text storage

set -e

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

# Default configuration (simplified from advanced system)
DATABASE_URL="${DATABASE_URL:-postgresql://postgres:postgres@localhost:5432/codex_store_db}"

print_banner() {
    echo -e "${BLUE}"
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║                Simple Text Storage Service Setup             ║"
    echo "║                Basic MCP Text Storage System                 ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
}

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

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

check_dependencies() {
    log_info "Checking system dependencies..."
    
    # Check if Rust/Cargo is installed
    if ! command -v cargo &> /dev/null; then
        log_error "Cargo not found. Please install Rust from https://rustup.rs/"
        exit 1
    fi
    
    # Check if PostgreSQL is available
    if ! command -v psql &> /dev/null; then
        log_warn "PostgreSQL client not found. Make sure PostgreSQL is accessible."
    fi
    
    log_info "✅ Dependency check completed"
    log_info "NOTE: This is a simple text storage system (no Ollama/embedding requirements)"
}

setup_environment() {
    log_info "Setting up environment configuration..."
    
    # Create .env file if it doesn't exist
    if [ ! -f .env ]; then
        log_info "Creating .env configuration file..."
        log_info "💡 Copy .env.example to .env and modify database credentials"
        cp .env.example .env
        log_info "✅ Configuration file created from .env.example"
    else
        log_info "✅ Environment file already exists"
    fi
}

setup_database() {
    log_info "Setting up database..."
    
    # Use actual CLI command that exists
    if cargo run --bin codex setup; then
        log_info "✅ Database setup completed"
    else
        log_error "❌ Database setup failed"
        log_info "💡 Please check your DATABASE_URL and PostgreSQL installation"
        return 1
    fi
}

test_basic_functionality() {
    log_info "Testing basic storage functionality..."
    
    # Test storage and retrieval
    log_info "Testing store/get operations..."
    if cargo run --bin codex stats > /dev/null 2>&1; then
        log_info "✅ Basic functionality test passed"
        return 0
    else
        log_error "❌ Basic functionality test failed"
        return 1
    fi
}

build_project() {
    log_info "Building project..."
    
    if cargo build --release; then
        log_info "✅ Build completed successfully"
    else
        log_error "❌ Build failed"
        return 1
    fi
}

quick_setup() {
    log_info "🚀 Running quick setup..."
    
    check_dependencies
    setup_environment
    
    # Build first to ensure we have the binary
    build_project || return 1
    
    setup_database || return 1
    test_basic_functionality || return 1
    
    log_info "🎉 Quick setup completed!"
    log_info "💡 Run functionality test with: ./scripts/setup.sh test"
    log_info "💡 Start the MCP server with: cargo run --bin codex mcp"
    log_info "💡 View storage stats with: cargo run --bin codex stats"
}

show_help() {
    echo "Simple Text Storage Service Setup Script"
    echo ""
    echo "Usage: $0 [command]"
    echo ""
    echo "Commands:"
    echo "  quick        Run complete setup (default)"
    echo "  deps         Check system dependencies"
    echo "  env          Setup environment configuration"
    echo "  database     Setup database and migrations"
    echo "  test         Test basic functionality"
    echo "  build        Build the project"
    echo "  mcp          Start MCP server (after setup)"
    echo "  help         Show this help message"
    echo ""
    echo "Environment variables:"
    echo "  DATABASE_URL    PostgreSQL connection URL"
    echo ""
    echo "Examples:"
    echo "  $0                    # Run quick setup"
    echo "  $0 test              # Test storage functionality"
    echo "  $0 mcp               # Start MCP server"
    echo "  DATABASE_URL=postgresql://user:pass@host:5432/db $0 quick"
}

# Main script logic
case "${1:-quick}" in
    "quick")
        print_banner
        quick_setup
        ;;
    "deps")
        print_banner
        check_dependencies
        ;;
    "env")
        print_banner
        setup_environment
        ;;
    "database")
        print_banner
        setup_database
        ;;
    "test")
        print_banner
        test_basic_functionality
        ;;
    "build")
        print_banner
        build_project
        ;;
    "mcp")
        print_banner
        log_info "Starting Simple Text Storage MCP Server..."
        cargo run --bin codex mcp
        ;;
    "help"|"-h"|"--help")
        print_banner
        show_help
        ;;
    *)
        log_error "Unknown command: $1"
        show_help
        exit 1
        ;;
esac