#!/bin/bash

# PCode Startup Script for macOS
# This is a template that will be copied to the package root as start.sh

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR/lib"

# Define common dotnet installation paths
DOTNET_COMMON_PATHS=(
    "$HOME/.dotnet/dotnet"
    "/usr/local/share/dotnet/dotnet"
    "/usr/share/dotnet/dotnet"
    "/usr/local/bin/dotnet"
    "/usr/bin/dotnet"
)

# Track what we've checked for error reporting
CHECKED_METHODS=""

# Find dotnet executable with enhanced detection logic
# Returns the path to dotnet if found, exits with error if not found
find_dotnet() {
    # 1. Check DOTNET_ROOT environment variable first
    if [ -n "$DOTNET_ROOT" ]; then
        CHECKED_METHODS="DOTNET_ROOT: $DOTNET_ROOT"
        if [ -x "$DOTNET_ROOT/dotnet" ]; then
            echo "$DOTNET_ROOT/dotnet"
            return 0
        fi
    fi

    # 2. Use command -v for PATH search
    local dotnet_path
    dotnet_path=$(command -v dotnet 2>/dev/null)
    if [ -n "$dotnet_path" ] && [ -x "$dotnet_path" ]; then
        CHECKED_METHODS="$CHECKED_METHODS; PATH (command -v): $dotnet_path"
        echo "$dotnet_path"
        return 0
    fi

    # 3. Use which as fallback PATH search
    dotnet_path=$(which dotnet 2>/dev/null)
    if [ -n "$dotnet_path" ] && [ -x "$dotnet_path" ]; then
        CHECKED_METHODS="$CHECKED_METHODS; PATH (which): $dotnet_path"
        echo "$dotnet_path"
        return 0
    fi

    # 4. Check predefined common paths
    local checked_paths=""
    for path in "${DOTNET_COMMON_PATHS[@]}"; do
        checked_paths="$checked_paths$path "
        if [ -x "$path" ]; then
            CHECKED_METHODS="$CHECKED_METHODS; Predefined paths: $path"
            echo "$path"
            return 0
        fi
    done

    # If we get here, dotnet was not found
    return 1
}

# Find dotnet runtime
DOTNET_PATH=$(find_dotnet)

if [ -z "$DOTNET_PATH" ]; then
    echo "Error: .NET runtime not found."
    echo ""
    echo "Checked the following locations:"
    echo "  - DOTNET_ROOT environment variable: ${DOTNET_ROOT:-not set}"
    echo "  - PATH search (command -v): $(command -v dotnet 2>/dev/null || echo 'not found')"
    echo "  - PATH search (which): $(which dotnet 2>/dev/null || echo 'not found')"
    echo "  - Common installation paths:"
    for path in "${DOTNET_COMMON_PATHS[@]}"; do
        echo "      $path"
    done
    echo ""
    echo "Please install .NET 10.0 runtime."
    echo "Visit: https://dotnet.microsoft.com/download/dotnet/10.0"
    exit 1
fi

# Start application
echo "Starting PCode..."
exec "$DOTNET_PATH" PCode.Web.dll
