#!/bin/bash
# description: Create a task plan with ordered steps as a markdown checklist
# Args: <goal> <step1> [step2] ...
# Output: relative path to the created plan file
set -euo pipefail

OLLIE="${OLLIE:-$HOME/mnt/ollie}"
PLAN_DIR="$OLLIE/pl"

if [ $# -eq 0 ]; then
    echo "usage: task_plan <goal> <step1> [step2] ..."
    exit 1
fi
GOAL="$1"
shift

if [ $# -eq 0 ]; then
    echo "error: at least one step required"
    exit 1
fi

if [ ! -d "$PLAN_DIR" ]; then
    echo "error: plan directory does not exist: $PLAN_DIR"
    exit 1
fi

TIMESTAMP=$(date '+%Y%m%dT%H%M%S')
UID8=$(cat /proc/sys/kernel/random/uuid 2>/dev/null | tr -d '-' | cut -c1-8 \
    || od -A n -t x1 /dev/urandom | tr -d ' \n' | cut -c1-8)
SLUG=$(printf '%s' "$GOAL" \
    | tr '[:upper:]' '[:lower:]' \
    | tr -cs 'a-z0-9' '-' \
    | sed 's/^-//;s/-$//' \
    | cut -c1-48)

FILENAME="${TIMESTAMP}_${UID8}--${SLUG}__todo.md"
FILEPATH="$PLAN_DIR/$FILENAME"

{
    printf '# %s\n\n' "$GOAL"
    for step in "$@"; do
        printf '- [ ] %s\n' "$step"
    done
} > "$FILEPATH" || { echo "error: failed to write $FILEPATH"; exit 1; }

echo "$FILENAME"
