#!/usr/bin/env bash
# wm-done: Manually mark a task as done (for tasks completed outside the dispatcher).
#
# Usage:
#   wm-done <task-id>          # mark task as done
#   wm-done --undo <task-id>   # unmark task (re-open it)

set -euo pipefail

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

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

die() { printf 'wm-done: %s\n' "$*" >&2; exit 1; }

undo=0
while [ $# -gt 0 ]; do
    case "$1" in
        --undo)  undo=1 ;;
        --help|-h) sed -n '2,/^$/{ s/^# //; s/^#//; p; }' "$0"; exit 0 ;;
        -*)      die "unknown flag: $1" ;;
        *)       break ;;
    esac
    shift
done

[ $# -lt 1 ] && die "usage: wm-done [--undo] <task-id>"
tid="$1"
[ -n "${TASK_TEMPLATE[$tid]:-}" ] || die "unknown task ID: $tid"

if [ "$undo" -eq 1 ]; then
    if task_is_done "$tid" "$DONE_FILE"; then
        grep -vxF "$tid" "$DONE_FILE" > "$DONE_FILE.tmp"
        mv "$DONE_FILE.tmp" "$DONE_FILE"
        printf '\033[1;33m↺ Task %s re-opened.\033[0m\n' "$tid"
    else
        echo "Task $tid is not marked as done."
    fi
else
    if task_is_done "$tid" "$DONE_FILE"; then
        echo "Task $tid is already done."
    else
        echo "$tid" >> "$DONE_FILE"
        printf '\033[1;32m✓ Task %s marked as done.\033[0m\n' "$tid"
    fi
fi
