#!/usr/bin/env bash
# wm-status: Live status of running wm-port agent sessions.
#
# Usage:
#   wm-status              # show all active wm-port sessions
#   wm-status --watch      # refresh every 2 seconds
#   wm-status --follow ID  # tail the chat log for a task

set -euo pipefail

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
TOOLS="$ROOT/tools/wm-port"
MOUNT="${OLLIE:-$HOME/mnt/ollie}"

source "$TOOLS/task-map.sh"

watch=0
follow=""

while [ $# -gt 0 ]; do
    case "$1" in
        --watch|-w) watch=1 ;;
        --follow|-f) follow="$2"; shift ;;
        --help|-h)  sed -n '2,/^$/{ s/^# //; s/^#//; p; }' "$0"; exit 0 ;;
        *)          follow="$1" ;;
    esac
    shift
done

# Follow mode: tail a specific task's session
if [ -n "$follow" ]; then
    session_dir="$MOUNT/s/wm-port-${follow}"
    [ -d "$session_dir" ] || {
        echo "No active session for task $follow" >&2
        exit 1
    }
    printf '\033[1mFollowing task %s (Ctrl-C to stop)\033[0m\n\n' "$follow"
    exec tail -f "$session_dir/chat"
fi

show_status() {
    local found=0
    
    # Read session index
    while IFS=$'\t' read -r sid state cwd backend model; do
        # Filter to wm-port sessions
        [[ "$sid" == wm-port-* ]] || continue
        
        local tid="${sid#wm-port-}"
        local tnum="${TASK_TEMPLATE[$tid]:-?}"
        local tname="${TEMPLATE_NAME[$tnum]:-unknown}"
        
        local color="\033[33m"  # yellow for thinking/calling
        [ "$state" = "idle" ] && color="\033[32m"  # green for idle
        [[ "$state" == failed* ]] && color="\033[31m"  # red for failed
        
        # Get usage if available
        local usage=""
        if [ -f "$MOUNT/s/$sid/usage" ]; then
            usage=$(cat "$MOUNT/s/$sid/usage" 2>/dev/null | tr '\n' ' ')
        fi
        
        printf '  %b%-8s\033[0m  %b%-20s\033[0m  T%s %s' \
            "$color" "$tid" "$color" "$state" "$tnum" "$tname"
        [ -n "$usage" ] && printf '  \033[90m(%s)\033[0m' "$usage"
        printf '\n'
        
        found=1
    done < <(cat "$MOUNT/s/idx" 2>/dev/null)
    
    [ "$found" -eq 0 ] && printf '  \033[90m(no active wm-port sessions)\033[0m\n'
}

if [ "$watch" -eq 1 ]; then
    while true; do
        clear
        printf '\033[1mwm-port Active Sessions\033[0m  (%s)\n\n' "$(date +%H:%M:%S)"
        show_status
        printf '\n\033[90mRefreshing every 2s. Ctrl-C to stop.\033[0m\n'
        sleep 2
    done
else
    printf '\033[1mwm-port Active Sessions\033[0m\n\n'
    show_status
fi
