#!/bin/bash
#
# YOLO-TS Inference Wrapper Shell Script
#
# This script calls YOLO-TS inference in the 'yolots' conda environment
# and handles the conda activation automatically.
#
# Usage:
#   ./scripts/yolo_ts_inference.sh <image_path> [--conf 0.25] [--imgsz 640]
#
# Example:
#   ./scripts/yolo_ts_inference.sh test_data/image.jpg --conf 0.20 --imgsz 1024
#

set -e  # Exit on error

# Get script directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# Load environment variables from .env if it exists
ENV_FILE="$PROJECT_ROOT/.env"
if [ -f "$ENV_FILE" ]; then
    # Export variables from .env (ignore comments and empty lines)
    set -a
    source <(grep -v '^#' "$ENV_FILE" | grep -v '^$' | sed 's/\r$//')
    set +a
fi

# Find conda
if [ -n "$CONDA_EXE" ]; then
    CONDA="$CONDA_EXE"
elif [ -f "$HOME/anaconda3/bin/conda" ]; then
    CONDA="$HOME/anaconda3/bin/conda"
elif [ -f "$HOME/miniconda3/bin/conda" ]; then
    CONDA="$HOME/miniconda3/bin/conda"
elif command -v conda &> /dev/null; then
    CONDA="conda"
else
    echo "Error: conda not found. Please install conda or set CONDA_EXE environment variable."
    exit 1
fi

# Check if yolots environment exists
if ! "$CONDA" env list | grep -q "^yolots "; then
    echo "Error: 'yolots' conda environment not found."
    echo ""
    echo "Please create it first:"
    echo "  conda create -n yolots python=3.11 -y"
    echo "  conda activate yolots"
    echo "  pip install torch torchvision"
    echo "  cd /tmp && git clone https://github.com/Heqiang-Huang/YOLO-TS.git"
    echo "  cd YOLO-TS && pip install -r requirements.txt"
    echo ""
    echo "See docs/YOLO_TS_SEPARATE_ENV_SETUP.md for detailed instructions."
    exit 1
fi

# Run inference in yolots environment
"$CONDA" run -n yolots python "$SCRIPT_DIR/yolo_ts_inference.py" "$@"
