#!/usr/bin/env bash

# ai-task
# Helper CLI to generate AI task prompts based on AI_TASK_TEMPLATE.md
# Usage:
#   scripts/ai-task build "Objective text" [scope...]
#   scripts/ai-task plan "Objective text" [scope...]

set -e

TYPE="$1"
OBJECTIVE="$2"
shift 2 || true
SCOPE=("$@")

if [[ -z "$TYPE" || -z "$OBJECTIVE" ]]; then
  echo "Usage: ai-task <plan|build> \"Objective\" [scope files...]"
  exit 1
fi

TYPE_LOWER=$(echo "$TYPE" | tr '[:upper:]' '[:lower:]')
TYPE_UPPER=$(echo "$TYPE_LOWER" | tr '[:lower:]' '[:upper:]')

DATE=$(date "+%Y-%m-%d %H:%M")
DAY=$(date "+%Y%m%d")

case "$TYPE_LOWER" in
  build)
    PREFIX="BUILD"
    ;;
  plan)
    PREFIX="PLAN"
    ;;
  *)
    echo "Error: task type must be 'plan' or 'build'"
    exit 1
    ;;
esac

WORKLOG_FILE="docs/ai-worklog.md"
LAST_SEQ=0

if [[ -f "$WORKLOG_FILE" ]]; then
  LAST_MATCH=$(grep -Eo "${PREFIX}-${DAY}-[0-9]{3}" "$WORKLOG_FILE" | tail -n 1 || true)
  if [[ -n "$LAST_MATCH" ]]; then
    LAST_SEQ=${LAST_MATCH##*-}
    LAST_SEQ=$((10#$LAST_SEQ))
  fi
fi

NEXT_SEQ=$(printf "%03d" $((LAST_SEQ + 1)))
TASK_ID="${PREFIX}-${DAY}-${NEXT_SEQ}"

# Build scope block
cat <<EOF
Task Type:
${TYPE_UPPER}

Task ID:
${TASK_ID}

Date:
${DATE}

Objective:
${OBJECTIVE}

Context:
<describe repository state if needed>

Scope:
EOF

if [ ${#SCOPE[@]} -gt 0 ]; then
  for item in "${SCOPE[@]}"; do
    printf '%s\n' "- ${item}"
  done
else
  printf '%s\n' "- <fill scope>"
fi

cat <<EOF

Requirements:
<describe expected behavior>

Constraints:
- follow AGENT_WORKFLOW.md
- keep scope minimal
- preserve existing behavior unless explicitly changed

Testing:
<describe expected tests>

Validation:
make fix
make quality

Logging requirements:
- append entry to docs/ai-worklog.md
- append entry to docs/ai-prompts.md
- include Date, Task ID, Agent, Scope
- use Task ID: ${TASK_ID}

Git requirements:
- do NOT commit or push unless explicitly requested

Expected Report:
- files changed
- behavior changes
- validation results
EOF
