#!/bin/bash
# SKCC Skimmer Runtime Script for Linux/macOS using uv
# Uses uv for fast dependency management and virtual environment handling

set -e  # Exit on any error

# Change to the script's directory (fixes running from wrong location)
cd "$(dirname "$0")" || exit 1

# Check if uv is installed
if ! command -v uv >/dev/null 2>&1; then
    echo "Error: uv is not installed or not in PATH"
    echo "Please install uv first:"
    echo "  1. Download from: https://github.com/astral-sh/uv"
    echo "  2. Or install via pip: pip install uv"
    echo "  3. Or install via pipx: pipx install uv" 
    echo "  4. Or install via curl: curl -LsSf https://astral.sh/uv/install.sh | sh"
    exit 1
fi

# Set Linux-specific virtual environment
export UV_PROJECT_ENVIRONMENT=.venv-linux

# Create/sync virtual environment - let uv handle Python version requirements
if ! uv sync --quiet; then
    echo "First sync attempt failed, trying to install Python 3.11 via uv..."
    if ! uv python install 3.11 --quiet; then
        echo "Failed to install Python 3.11 via uv"
        echo "Please install Python 3.11+ manually using your package manager:"
        echo ""
        echo "Ubuntu/Debian: sudo apt-get install python3.11"
        echo "RHEL/CentOS/Fedora: sudo yum install python3.11"
        echo "macOS: brew install python@3.11"
        echo "Arch Linux: sudo pacman -S python"
        echo "Or download from: https://www.python.org/downloads/"
        exit 1
    fi
    
    echo "Python 3.11 installed, retrying environment sync..."
    if ! uv sync --quiet; then
        echo "Environment sync still failed, cleaning old virtual environment..."
        rm -rf .venv
        
        echo "Final attempt with fresh virtual environment..."
        if ! uv sync --quiet; then
            echo "Error: Failed to create virtual environment"
            echo "Make sure pyproject.toml exists and is valid"
            exit 1
        fi
    fi
fi

# Generate version stamp if .git exists (directory or file for submodules)
if [ -d .git ] || [ -f .git ]; then
    # Try to get tag first
    if VERSION=$(git describe --tags --exact-match HEAD 2>/dev/null); then
        GIT_SHA=$(git rev-list -n 1 "$VERSION")
    else
        # No tag, use current commit
        GIT_SHA=$(git rev-parse HEAD)
        VERSION=$(git rev-parse --short HEAD)
    fi
    
    # Check for modified files
    if [ -n "$(git status --porcelain)" ]; then
        VERSION="${VERSION}-"
    fi
    
    # Get commit date and short SHA
    COMMIT_DATE=$(git show -s --format=%as "$GIT_SHA")
    SHORT_SHA=$(git rev-parse --short "$GIT_SHA")
    
    # Create version stamp
    if [ "$VERSION" = "$SHORT_SHA" ]; then
        VERSION_STAMP="$VERSION / $COMMIT_DATE"
    else
        VERSION_STAMP="$VERSION / $COMMIT_DATE ($SHORT_SHA)"
    fi
    
    # Write cVersion.py
    echo "VERSION = '$VERSION_STAMP'" > cVersion.py
fi

# Run the application with all command line arguments using uv
uv run skcc_skimmer.py "$@"