#!/bin/bash

# Rustelo Local Development Helper Script
# This script sets up the environment for local template development

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

# Get the directory where this script is located
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# Set the default template source to the local templates
TEMPLATES_DIR="${RUSTELO_TEMPLATES_DIR:-$SCRIPT_DIR/templates}"

# Function to print colored output
print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

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

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

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

# Check if templates directory exists
if [ ! -d "$TEMPLATES_DIR" ]; then
    print_error "Templates directory not found: $TEMPLATES_DIR"
    echo "Please ensure you're running this script from the rustelo repository root."
    exit 1
fi

# Check if templates.json exists
if [ ! -f "$TEMPLATES_DIR/templates.json" ]; then
    print_error "templates.json not found in $TEMPLATES_DIR"
    echo "The templates directory appears to be incomplete."
    exit 1
fi

# Set RUSTELO_ASSET_SOURCE if not already set
export RUSTELO_ASSET_SOURCE="${RUSTELO_ASSET_SOURCE:-$TEMPLATES_DIR}"

print_success "Local development environment configured!"
print_info "Using templates from: $TEMPLATES_DIR"
if [ "$RUSTELO_ASSET_SOURCE" != "$TEMPLATES_DIR" ]; then
    print_info "RUSTELO_ASSET_SOURCE overridden to: $RUSTELO_ASSET_SOURCE"
fi
echo ""

# Determine which rustelo binary to use
DEBUG_BINARY="${RUSTELO_DEBUG_BINARY:-$SCRIPT_DIR/target/debug/cargo-rustelo}"
RELEASE_INSTALLED="${RUSTELO_RELEASE_BINARY:-$(command -v cargo-rustelo 2>/dev/null || true)}"

# Function to get the appropriate rustelo command
get_rustelo_cmd() {
    local command_type="$1"

    case "$command_type" in
        "production"|"release"|"install")
            # Use installed cargo rustelo for production tasks
            if [ -n "$RELEASE_INSTALLED" ]; then
                echo "cargo rustelo"
            elif [ -x "$DEBUG_BINARY" ]; then
                print_warning "Using debug binary for production command. Consider installing: cargo install --path crates/rustelo-cli"
                echo "$DEBUG_BINARY"
            else
                print_error "No rustelo binary available. Build with: cargo build"
                return 1
            fi
            ;;
        "dev"|"test"|"debug")
            # Use debug binary for development and testing (latest changes)
            if [ -x "$DEBUG_BINARY" ]; then
                echo "$DEBUG_BINARY"
            elif [ -n "$RELEASE_INSTALLED" ]; then
                print_info "Debug binary not found, using installed cargo rustelo"
                echo "cargo rustelo"
            else
                print_error "No rustelo binary available. Build with: cargo build --bin cargo-rustelo"
                return 1
            fi
            ;;
        *)
            # Default: prefer debug for local development, fallback to installed
            if [ -x "$DEBUG_BINARY" ]; then
                echo "$DEBUG_BINARY"
            elif [ -n "$RELEASE_INSTALLED" ]; then
                echo "cargo rustelo"
            else
                print_error "No rustelo binary available. Build with: cargo build --bin cargo-rustelo"
                return 1
            fi
            ;;
    esac
}

# Check binary availability and provide guidance
if [ -x "$DEBUG_BINARY" ]; then
    print_success "Debug binary available: $DEBUG_BINARY"
else
    print_info "Debug binary not found. Build with: cargo build --bin cargo-rustelo"
fi

if [ -n "$RELEASE_INSTALLED" ]; then
    print_success "Release binary installed: $RELEASE_INSTALLED"
else
    print_info "Release binary not installed. Install with: cargo install --path crates/rustelo-cli"
fi

echo ""

# Handle commands
case "$1" in
    init)
        shift
        RUSTELO_CMD=$(get_rustelo_cmd "dev")
        if [ $? -ne 0 ]; then exit 1; fi

        print_info "Creating new Rustelo project with local templates..."
        echo "Running: $RUSTELO_CMD init $@"
        echo ""
        $RUSTELO_CMD init "$@"
        ;;

    update)
        shift
        RUSTELO_CMD=$(get_rustelo_cmd "dev")
        if [ $? -ne 0 ]; then exit 1; fi

        print_info "Updating Rustelo project with local templates..."
        echo "Running: $RUSTELO_CMD update $@"
        $RUSTELO_CMD update "$@"
        ;;

    features)
        shift
        RUSTELO_CMD=$(get_rustelo_cmd "dev")
        if [ $? -ne 0 ]; then exit 1; fi

        print_info "Managing features with local configuration..."
        echo "Running: $RUSTELO_CMD features $@"
        $RUSTELO_CMD features "$@"
        ;;

    assets)
        shift
        RUSTELO_CMD=$(get_rustelo_cmd "dev")
        if [ $? -ne 0 ]; then exit 1; fi

        print_info "Managing assets with local source..."
        echo "Running: $RUSTELO_CMD assets $@"
        $RUSTELO_CMD assets "$@"
        ;;

    test)
        # Quick test to verify templates are accessible
        RUSTELO_CMD=$(get_rustelo_cmd "test")
        if [ $? -ne 0 ]; then exit 1; fi

        print_info "Testing template discovery with debug binary..."
        echo "Running: $RUSTELO_CMD init (test project)"
        echo ""

        # Create a temporary test project
        TEST_DIR="/tmp/rustelo-test-$$"
        $RUSTELO_CMD init "$TEST_DIR" --template minimal

        if [ $? -eq 0 ]; then
            print_success "Template system is working correctly!"
            rm -rf "$TEST_DIR"
        else
            print_error "Template system test failed"
        fi
        ;;

    list)
        # List available templates
        print_info "Available templates in $TEMPLATES_DIR:"
        echo ""

        if command -v jq &> /dev/null; then
            jq -r '.[] | "  \(.icon // "📦") \(.name) - \(.description)"' "$TEMPLATES_DIR/templates.json"
        else
            echo "  Install 'jq' for formatted template listing"
            echo "  Templates defined in: $TEMPLATES_DIR/templates.json"
        fi
        ;;

    env)
        # Show current environment
        print_info "Current Rustelo environment:"
        echo "  RUSTELO_ASSET_SOURCE=$RUSTELO_ASSET_SOURCE"
        echo "  RUSTELO_TEMPLATES_DIR=${RUSTELO_TEMPLATES_DIR:-<default>}"
        echo "  RUSTELO_DEBUG_BINARY=${RUSTELO_DEBUG_BINARY:-<default>}"
        echo "  RUSTELO_RELEASE_BINARY=${RUSTELO_RELEASE_BINARY:-<auto-detected>}"
        echo ""
        echo "  Templates directory: $TEMPLATES_DIR"
        echo "  Script directory: $SCRIPT_DIR"
        echo ""

        # Check for other relevant environment variables
        if [ ! -z "$RUST_LOG" ]; then
            echo "  RUST_LOG=$RUST_LOG"
        fi

        echo ""
        echo "Binary Selection:"
        if [ -x "$DEBUG_BINARY" ]; then
            echo "  Debug: $DEBUG_BINARY (preferred for dev/test)"
        else
            echo "  Debug: Not available - run 'cargo build --bin cargo-rustelo'"
        fi

        if [ -n "$RELEASE_INSTALLED" ]; then
            echo "  Release: $RELEASE_INSTALLED (preferred for production)"
        else
            echo "  Release: Not installed - run 'cargo install --path crates/rustelo-cli'"
        fi
        ;;

    build)
        # Build the debug binary for local development
        print_info "Building debug binary for local development..."
        echo "Running: cargo build --bin cargo-rustelo"
        echo ""
        cargo build --bin cargo-rustelo

        if [ $? -eq 0 ]; then
            print_success "Debug binary built successfully!"
            print_info "Binary location: $DEBUG_BINARY"
        else
            print_error "Build failed"
        fi
        ;;

    install)
        # Install release binary for production use
        RUSTELO_CMD=$(get_rustelo_cmd "production")
        print_info "Installing release binary for production use..."
        echo "Running: cargo install --path crates/rustelo-cli"
        echo ""
        cargo install --path crates/rustelo-cli

        if [ $? -eq 0 ]; then
            print_success "Release binary installed successfully!"
            print_info "Now available as: cargo rustelo"
        else
            print_error "Installation failed"
        fi
        ;;

    help|--help|-h|"")
        echo "Rustelo Local Development Helper"
        echo ""
        echo "This script configures the environment to use local templates"
        echo "from: $TEMPLATES_DIR"
        echo ""
        echo "Usage: $0 <command> [options]"
        echo ""
        echo "Commands:"
        echo "  init <name> [opts]  Create a new project with local templates (uses debug binary)"
        echo "  update [opts]       Update a project using local templates (uses debug binary)"
        echo "  features [opts]     Manage features with local configuration (uses debug binary)"
        echo "  assets [opts]       Manage assets with local source (uses debug binary)"
        echo "  test               Test that local templates are working (uses debug binary)"
        echo "  list               List available local templates"
        echo "  env                Show current environment and binary settings"
        echo "  build              Build debug binary for local development"
        echo "  install            Install release binary for production use"
        echo "  help               Show this help message"
        echo ""
        echo "Binary Selection Logic:"
        echo "  • Development commands (init, update, features, assets, test) prefer debug binary"
        echo "  • Production commands (install) prefer release binary"
        echo "  • Debug binary: faster iteration, includes latest changes"
        echo "  • Release binary: optimized, suitable for production workflows"
        echo ""
        echo "Environment Variables (optional overrides):"
        echo "  RUSTELO_ASSET_SOURCE    - Override template source directory"
        echo "  RUSTELO_TEMPLATES_DIR   - Override local templates directory"
        echo "  RUSTELO_DEBUG_BINARY    - Override debug binary path"
        echo "  RUSTELO_RELEASE_BINARY  - Override release binary path"
        echo ""
        echo "Examples:"
        echo "  $0 init my-app"
        echo "  $0 init my-app --template enterprise"
        echo "  $0 test"
        echo "  $0 list"
        echo ""
        echo "For more options, use: cargo rustelo <command> --help"
        ;;

    *)
        print_error "Unknown command: $1"
        echo "Run '$0 help' for usage information"
        exit 1
        ;;
esac
