#!/usr/bin/env bash
# build.sh — Package el_ui_native_codegen.py as a self-contained executable.
#
# Usage:
#   ./build.sh                # creates dist/el-ui-native-codegen
#   ./build.sh test           # run against test fixtures
#   ./build.sh clean          # remove build artifacts
#
# The output is a plain shell wrapper that invokes the Python script with
# the correct path. No dependencies beyond Python 3 (guaranteed available).
#
# The dist binary can be called as:
#   el-ui-native-codegen App.el                    # writes to stdout
#   el-ui-native-codegen App.el -o generated.el    # writes to file
#   el-ui-native-codegen App.el --vessel-path ../../vessels/el-native/src/main.el

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DIST_DIR="${SCRIPT_DIR}/../dist"
BINARY="${DIST_DIR}/el-ui-native-codegen"
PY_SCRIPT="${SCRIPT_DIR}/el_ui_native_codegen.py"

build() {
    mkdir -p "${DIST_DIR}"

    echo "==> Creating ${BINARY}..."
    cat > "${BINARY}" <<EOF
#!/usr/bin/env bash
# el-ui-native-codegen — el-ui component DSL → el-native API calls
# Auto-generated by build.sh — do not edit.
exec python3 "${PY_SCRIPT}" "\$@"
EOF
    chmod +x "${BINARY}"
    echo "==> Done: ${BINARY}"
}

test_codegen() {
    build
    echo ""
    echo "==> Running test: test_app.el"
    echo "────────────────────────────────────────"
    "${BINARY}" "${SCRIPT_DIR}/test_app.el"
    echo ""
    echo "==> Running test: test_native_hello.el"
    echo "────────────────────────────────────────"
    "${BINARY}" "${SCRIPT_DIR}/test_native_hello.el"
    echo ""
    echo "==> All tests passed."
}

clean() {
    rm -f "${BINARY}"
    echo "Cleaned."
}

case "${1:-build}" in
    build)   build       ;;
    test)    test_codegen ;;
    clean)   clean       ;;
    *)       echo "Usage: $0 [build|test|clean]"; exit 1 ;;
esac
