#!/usr/bin/env bash
# wm-tasks: Show task status for the WindowMaker Wayland port.
#
# Usage:
#   wm-tasks                  # show all tasks grouped by wave
#   wm-tasks --wave <N>       # show tasks in wave N only
#   wm-tasks --ready          # show only unblocked, undone tasks
#   wm-tasks --done            # show only completed tasks
#   wm-tasks --blocked         # show only blocked tasks
#   wm-tasks <task-id>        # show details for one task

set -euo pipefail

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
TOOLS="$ROOT/tools/wm-port"
DONE_FILE="$TOOLS/done.txt"
LOG_DIR="$TOOLS/logs"

source "$TOOLS/task-map.sh"
touch "$DONE_FILE"

filter="all"
filter_wave=""
detail_id=""

while [ $# -gt 0 ]; do
    case "$1" in
        --wave)    filter_wave="$2"; shift ;;
        --ready)   filter="ready" ;;
        --done)    filter="done" ;;
        --blocked) filter="blocked" ;;
        --help|-h) sed -n '2,/^$/{ s/^# //; s/^#//; p; }' "$0"; exit 0 ;;
        -*)        echo "wm-tasks: unknown flag: $1" >&2; exit 1 ;;
        *)         detail_id="$1" ;;
    esac
    shift
done

# Detail view for a single task
if [ -n "$detail_id" ]; then
    [ -n "${TASK_TEMPLATE[$detail_id]:-}" ] || { echo "Unknown task: $detail_id" >&2; exit 1; }
    tnum="${TASK_TEMPLATE[$detail_id]}"
    wave="${TASK_WAVE[$detail_id]:-?}"
    blockers="${TASK_BLOCKERS[$detail_id]:-none}"
    
    if task_is_done "$detail_id" "$DONE_FILE"; then
        status="\033[1;32mDONE\033[0m"
    elif task_is_unblocked "$detail_id" "$DONE_FILE"; then
        status="\033[1;36mREADY\033[0m"
    else
        status="\033[1;33mBLOCKED\033[0m"
    fi
    
    printf 'Task:     %s\n' "$detail_id"
    printf 'Template: %s (%s)\n' "$tnum" "${TEMPLATE_NAME[$tnum]}"
    printf 'Wave:     %s\n' "$wave"
    printf 'Blockers: %s\n' "$blockers"
    printf 'Status:   %b\n' "$status"
    
    if [ -f "$LOG_DIR/${detail_id}.log" ]; then
        printf 'Log:      %s\n' "$LOG_DIR/${detail_id}.log"
        echo
        echo "--- Last 20 lines of log ---"
        tail -20 "$LOG_DIR/${detail_id}.log"
    fi
    
    # Check for active session
    local_session="$OLLIE/s/wm-port-${detail_id}"
    if [ -d "${OLLIE:-$HOME/mnt/ollie}/s/wm-port-${detail_id}" ]; then
        state=$(cat "${OLLIE:-$HOME/mnt/ollie}/s/wm-port-${detail_id}/state" 2>/dev/null || echo "unknown")
        printf 'Session:  wm-port-%s (%s)\n' "$detail_id" "$state"
    fi
    exit 0
fi

# Summary view
total=0
done_count=0
ready_count=0
blocked_count=0

# Collect stats
while IFS= read -r tid; do
    (( ++total ))
    if task_is_done "$tid" "$DONE_FILE"; then
        (( ++done_count ))
    elif task_is_unblocked "$tid" "$DONE_FILE"; then
        (( ++ready_count ))
    else
        (( ++blocked_count ))
    fi
done < <(task_all_ids)

printf '\033[1mWindowMaker Wayland Port: %d/%d tasks done, %d ready, %d blocked\033[0m\n\n' \
    "$done_count" "$total" "$ready_count" "$blocked_count"

# Print by wave
for w in 0 1 2 3; do
    [ -n "$filter_wave" ] && [ "$filter_wave" != "$w" ] && continue
    
    wave_label="Wave $w"
    [ "$w" -eq 0 ] && wave_label="Immediate"
    
    wave_tasks=()
    while IFS= read -r tid; do
        [ "${TASK_WAVE[$tid]:-}" = "$w" ] || continue
        wave_tasks+=("$tid")
    done < <(task_all_ids)
    
    [ ${#wave_tasks[@]} -eq 0 ] && continue
    
    printed_header=0
    for tid in "${wave_tasks[@]}"; do
        tnum="${TASK_TEMPLATE[$tid]}"
        
        if task_is_done "$tid" "$DONE_FILE"; then
            [ "$filter" = "ready" ] || [ "$filter" = "blocked" ] && continue
            icon="\033[32m✓\033[0m"
            label=""
        elif task_is_unblocked "$tid" "$DONE_FILE"; then
            [ "$filter" = "done" ] || [ "$filter" = "blocked" ] && continue
            icon="\033[36m○\033[0m"
            label=""
            # Check if running
            if [ -d "${OLLIE:-$HOME/mnt/ollie}/s/wm-port-${tid}" ]; then
                state=$(cat "${OLLIE:-$HOME/mnt/ollie}/s/wm-port-${tid}/state" 2>/dev/null || echo "?")
                icon="\033[33m●\033[0m"
                label=" [$state]"
            fi
        else
            [ "$filter" = "done" ] || [ "$filter" = "ready" ] && continue
            icon="\033[90m•\033[0m"
            blockers="${TASK_BLOCKERS[$tid]:-}"
            pending=""
            for dep in $blockers; do
                task_is_done "$dep" "$DONE_FILE" || pending="$pending $dep"
            done
            label="\033[90m blocked by:$pending\033[0m"
        fi
        
        if [ "$printed_header" -eq 0 ]; then
            printf '\033[1;4m%s\033[0m\n' "$wave_label"
            printed_header=1
        fi
        
        printf '  %b %-8s T%s %-35s%b\n' \
            "$icon" "$tid" "$tnum" "${TEMPLATE_NAME[$tnum]}" "$label"
    done
    
    [ "$printed_header" -eq 1 ] && echo
done

# Legend
printf '\033[90mLegend: \033[32m✓\033[90m done  \033[36m○\033[90m ready  \033[33m●\033[90m running  \033[90m• blocked\033[0m\n'
