#!/usr/bin/env bash
set -euo pipefail

usage() {
  echo "Usage: ai/commands/new-chunk.sh <slug> [draft|backlog|active]" >&2
}

repo_root() {
  local script_dir
  script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  if git -C "$script_dir" rev-parse --show-toplevel >/dev/null 2>&1; then
    git -C "$script_dir" rev-parse --show-toplevel
    return
  fi
  cd "$script_dir/../.." && pwd
}

status_for_target() {
  case "$1" in
    drafts) echo "Draft" ;;
    backlog) echo "Backlog" ;;
    active) echo "Active" ;;
    *) return 1 ;;
  esac
}

ensure_no_active_chunk() {
  local active_dir="$1"
  local active_count=0
  shopt -s nullglob
  local active_files=("$active_dir"/chunk-[0-9]*-*.md)
  shopt -u nullglob
  active_count="${#active_files[@]}"

  if (( active_count > 0 )); then
    echo "An active chunk already exists: ${active_files[0]}" >&2
    exit 1
  fi
}

next_chunk_id() {
  local chunks_dir="$1"
  local max_id=0
  local file filename id

  shopt -s nullglob
  for file in "$chunks_dir"/{drafts,backlog,active,completed}/chunk-[0-9]*-*.md; do
    filename="$(basename "$file")"
    id="${filename#chunk-}"
    id="${id%%-*}"
    if (( 10#$id > max_id )); then
      max_id=$((10#$id))
    fi
  done
  shopt -u nullglob

  printf '%06d\n' "$((max_id + 1))"
}

if [[ $# -lt 1 || $# -gt 2 ]]; then
  usage
  exit 2
fi

slug="$1"
target="${2:-draft}"

if [[ ! "$slug" =~ ^[a-z0-9]+(-[a-z0-9]+)*$ ]]; then
  echo "Slug must be kebab-case: $slug" >&2
  exit 1
fi

case "$target" in
  draft) target_dir_name="drafts" ;;
  backlog) target_dir_name="backlog" ;;
  active) target_dir_name="active" ;;
  *)
    echo "Target must be one of: draft, backlog, active" >&2
    exit 1
    ;;
esac

root="$(repo_root)"
chunks_dir="$root/ai/chunks"
target_dir="$chunks_dir/$target_dir_name"
active_dir="$chunks_dir/active"

if [[ ! -d "$target_dir" ]]; then
  echo "Chunk target directory does not exist: $target_dir" >&2
  exit 1
fi

if [[ "$target_dir_name" == "active" ]]; then
  ensure_no_active_chunk "$active_dir"
fi

chunk_id="$(next_chunk_id "$chunks_dir")"
filename="chunk-${chunk_id}-${slug}.md"
destination="$target_dir/$filename"

if [[ -e "$destination" ]]; then
  echo "Chunk already exists: $destination" >&2
  exit 1
fi

stdin_file="$(mktemp)"
trap 'rm -f "$stdin_file"' EXIT

if [[ ! -t 0 ]]; then
  cat > "$stdin_file"
fi

created="$(date -u +%Y-%m-%dT%H:%M:%S.000Z)"
status="$(status_for_target "$target_dir_name")"

{
  cat <<EOF
---
Status: $status
Owner Role: Developer
Created: $created
Completed:
Depends On:
Validation: ai/commands/validate.sh
---

EOF

  if [[ -s "$stdin_file" ]]; then
    cat "$stdin_file"
  else
    cat "$root/ai/tasks/feature-template.md"
  fi
} > "$destination"

echo "$destination"
