#!/bin/bash
# Manage 'latest' symlink for parallel-dev runs

RUNS_DIR=".bmad-workspace/ck-parallel-dev/runs"
LATEST_LINK="$RUNS_DIR/latest"

# Function to update latest symlink
update_latest() {
    if [ ! -d "$RUNS_DIR" ]; then
        echo "Error: Runs directory not found: $RUNS_DIR"
        exit 1
    fi
    
    # Find the most recent run directory
    LATEST_RUN=$(ls -t "$RUNS_DIR" | grep -E '^[0-9]{8}-[0-9]{6}-[a-z0-9]{6}$' | head -1)
    
    if [ -z "$LATEST_RUN" ]; then
        echo "No run directories found"
        exit 1
    fi
    
    # Remove existing symlink if it exists
    if [ -L "$LATEST_LINK" ]; then
        rm "$LATEST_LINK"
    fi
    
    # Create new symlink
    ln -s "$LATEST_RUN" "$LATEST_LINK"
    echo "Updated latest symlink to: $LATEST_RUN"
}

# Function to verify latest symlink
verify_latest() {
    if [ ! -L "$LATEST_LINK" ]; then
        echo "Latest symlink does not exist"
        return 1
    fi
    
    TARGET=$(readlink "$LATEST_LINK")
    if [ ! -d "$RUNS_DIR/$TARGET" ]; then
        echo "Latest symlink points to non-existent directory: $TARGET"
        return 1
    fi
    
    echo "Latest symlink is valid: $TARGET"
    return 0
}

# Main script
case "${1:-update}" in
    update)
        update_latest
        ;;
    verify)
        verify_latest
        ;;
    *)
        echo "Usage: $0 [update|verify]"
        echo "  update - Update latest symlink to most recent run"
        echo "  verify - Verify latest symlink is valid"
        exit 1
        ;;
esac