#!/usr/bin/env bash
# tunectl — npm/npx shim that delegates to the Python CLI.
#
# This script is the bin entry point for the npm package. It checks
# that python3 is available, then invokes `python3 -m tunectl` with
# all arguments forwarded unchanged.

set -euo pipefail

# Resolve the package root (one level up from bin/).
# Follow symlinks so npm link / npx scenarios resolve correctly.
SOURCE="${BASH_SOURCE[0]}"
while [[ -L "$SOURCE" ]]; do
    DIR="$(cd "$(dirname "$SOURCE")" && pwd)"
    SOURCE="$(readlink "$SOURCE")"
    # Handle relative symlinks
    [[ "$SOURCE" != /* ]] && SOURCE="$DIR/$SOURCE"
done
PACKAGE_ROOT="$(cd "$(dirname "$SOURCE")/.." && pwd)"

# Check that python3 is available
if ! command -v python3 &>/dev/null; then
    echo "Error: python3 is required but was not found on PATH." >&2
    echo "" >&2
    echo "Install Python 3 for your platform:" >&2
    echo "  Ubuntu/Debian:  sudo apt install python3" >&2
    echo "  macOS:          brew install python3" >&2
    echo "  Fedora/RHEL:    sudo dnf install python3" >&2
    echo "  Arch Linux:     sudo pacman -S python" >&2
    echo "" >&2
    echo "Then re-run: npx tunectl $*" >&2
    exit 1
fi

# Ensure the tunectl Python package is importable by adding the
# package root to PYTHONPATH (needed for npm link / npx scenarios
# where the package is not pip-installed).
export PYTHONPATH="${PACKAGE_ROOT}${PYTHONPATH:+:$PYTHONPATH}"

# Delegate to the Python CLI, running from the package root so that
# scripts/ and tune-manifest.json are located correctly.
cd "$PACKAGE_ROOT"
exec python3 -m tunectl "$@"
