#!/bin/bash
# Normal CLI wrapper - auto-installs and runs installed bin/normal bash script

# Resolve symlinks to find the real script location
SOURCE="${BASH_SOURCE[0]}"
while [[ -L "$SOURCE" ]]; do
    DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
    SOURCE="$(readlink "$SOURCE")"
    [[ "$SOURCE" != /* ]] && SOURCE="$DIR/$SOURCE"
done
SCRIPT_DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
NORMAL_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# Preserve original PATH so run_bash can restore it for external tools
export _NORMAL_ORIGINAL_PATH="$PATH"

# Add bundled Python and tools to PATH
export PATH="$NORMAL_ROOT/python/bin:$NORMAL_ROOT/bin:$PATH"

# Export NORMAL_ROOT so the installed script can find bundled config
export NORMAL_ROOT

# Auto-install on first run
if [[ ! -f "$NORMAL_ROOT/.installed" ]]; then
    "$SCRIPT_DIR/install-packages.sh"
fi

is_wrapper_path_arg() {
    case "$1" in
        /*|./*|../*|*/*) return 0 ;;
        *) return 1 ;;
    esac
}

# Deployment installers may prepend wrapper-only state roots before the
# Normal command. Stop parsing at the first real command/option so downstream
# flags such as `normal run -c 8` remain untouched.
while [[ $# -gt 0 ]]; do
    case "$1" in
        -c)
            if [[ $# -lt 2 ]] || ! is_wrapper_path_arg "$2"; then
                break
            fi
            export NORMAL_CONFIG_BASEDIR="$2/config"
            export NORMAL_CONFIG="$NORMAL_CONFIG_BASEDIR/config"
            export NORMAL_MCP_CONFIG="$NORMAL_CONFIG_BASEDIR/mcp/servers.yaml"
            shift 2
            ;;
        -h)
            if [[ $# -lt 2 ]] || ! is_wrapper_path_arg "$2"; then
                break
            fi
            export NORMAL_HOME="$2/home"
            export NORMAL_LOGDIR="$NORMAL_HOME/logs"
            shift 2
            ;;
        --)
            shift
            break
            ;;
        *)
            break
    esac
done

# Detect Python version and run the installed normal bash script from site-packages
PYTHON_VERSION=$("$NORMAL_ROOT/python/bin/python3.14" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')")
exec "$NORMAL_ROOT/python/lib/python$PYTHON_VERSION/site-packages/nectar2/bin/normal" "$@"
