#!/bin/bash
# description: Create a task plan as a markdown checklist tagged __todo
# Args: <goal> <task1> [task2] ...
# Output: plan filename in pl/
set -euo pipefail

if [ "${OLLIE_BEADS_ENABLE:-0}" = "1" ] && command -v bd >/dev/null 2>&1 && [ -f ".beads" ]; then
    echo "error: beads is available — use 'bd' for planning instead of plan_create" >&2
    exit 2
fi

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

if [ $# -lt 2 ]; then
    echo "usage: plan_create <goal> <task1> [task2] ..."
    exit 1
fi

GOAL="$1"; shift

[ -d "$PLAN_DIR" ] || { echo "error: plan directory not found: $PLAN_DIR"; exit 1; }

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 task in "$@"; do
        printf -- '- [ ] %s\n' "$task"
    done
} > "$FILEPATH" || { echo "error: failed to write $FILEPATH"; exit 1; }

echo "$FILENAME"
