#!/bin/bash
# Taskmaster Tracker Script
# Wrapper for the Python taskmaster_tracker.py script

set -e

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

# Change to project root
cd "$PROJECT_ROOT"

# Check if uv is available
if ! command -v uv &> /dev/null; then
    echo "Error: uv package manager not found. Please install uv first."
    exit 1
fi

# Use uv run for Python execution
PYTHON_CMD="uv run python"

# Function to show usage
show_usage() {
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  --watch              Watch for changes continuously"
    echo "  --interval SECONDS   Watch interval in seconds (default: 5.0)"
    echo "  --once               Run once and exit (default)"
    echo "  --help               Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0 --once                    # Run once and exit"
    echo "  $0 --watch                   # Watch continuously with 5s interval"
    echo "  $0 --watch --interval 10     # Watch with 10s interval"
    echo ""
    echo "The tracker will:"
    echo "  - Add 'created_at' timestamps to new tasks"
    echo "  - Add 'updated_at' timestamps when tasks change"
    echo "  - Add 'status_changed_to_X' timestamps for status changes"
    echo "  - Create backups before making changes"
    echo "  - Log all activities to logs/taskmaster_tracker.log"
}

# Parse command line arguments
WATCH_MODE=false
INTERVAL=5.0
RUN_ONCE=true

while [[ $# -gt 0 ]]; do
    case $1 in
        --watch)
            WATCH_MODE=true
            RUN_ONCE=false
            shift
            ;;
        --interval)
            INTERVAL="$2"
            shift 2
            ;;
        --once)
            RUN_ONCE=true
            WATCH_MODE=false
            shift
            ;;
        --help|-h)
            show_usage
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            show_usage
            exit 1
            ;;
    esac
done

# Check if Python script exists
PYTHON_SCRIPT="$SCRIPT_DIR/taskmaster_tracker.py"
if [[ ! -f "$PYTHON_SCRIPT" ]]; then
    echo "Error: taskmaster_tracker.py not found at $PYTHON_SCRIPT"
    exit 1
fi

# Make sure the script is executable
chmod +x "$PYTHON_SCRIPT"

# Run the tracker
echo "Starting Taskmaster Tracker..."
echo "Project root: $PROJECT_ROOT"
echo "Python script: $PYTHON_SCRIPT"

if [[ "$WATCH_MODE" == true ]]; then
    echo "Watch mode enabled (interval: ${INTERVAL}s)"
    echo "Press Ctrl+C to stop"
    echo ""
    $PYTHON_CMD "$PYTHON_SCRIPT" --watch --interval "$INTERVAL"
else
    echo "Running once..."
    $PYTHON_CMD "$PYTHON_SCRIPT"
fi
