#!/usr/bin/env bash
# flow — deadly-simple driver for the Skirmisher AI-native SDLC.
#
#   flow new <feature> ["one-line problem"]   scaffold a feature + intent.md
#   flow next <feature>                        create the next artifact (spec → plan)
#   flow status [feature]                      show where each feature stands
#   flow test                                  run all checks (the pytest suite)
#   flow ship <feature>                        run checks, mark shipped, show the diff
#   flow help                                  this text
#
# The chain:  intent.md -> spec.md -> plan.md -> build -> test -> ship.
# One artifact per stage. Fill each in, then `flow next`. See docs/sdlc/PLAYBOOK.md.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")" && pwd)"
FEAT="$ROOT/docs/features"
TPL="$ROOT/docs/sdlc/templates"
PY="$ROOT/.venv/bin/python"; [ -x "$PY" ] || PY="python3"

c_red=$'\033[91m'; c_grn=$'\033[32m'; c_dim=$'\033[90m'; c_cy=$'\033[36m'; c_0=$'\033[0m'
[ -t 1 ] || { c_red=; c_grn=; c_dim=; c_cy=; c_0=; }

die(){ printf '%serror:%s %s\n' "$c_red" "$c_0" "$*" >&2; exit 2; }
slug(){ printf '%s' "$1" | tr '[:upper:] ' '[:lower:]-' | tr -cd 'a-z0-9-'; }
today(){ date +%Y-%m-%d; }

scaffold(){  # scaffold <template> <dest> <feature> <slug> [summary]
  local tpl="$1" dest="$2" feature="$3" s="$4" summary="${5:-}"
  FEATURE="$feature" SLUG="$s" DATE="$(today)" SUMMARY="$summary" \
  "$PY" - "$tpl" "$dest" <<'PY'
import os, sys
tpl, dest = sys.argv[1], sys.argv[2]
text = open(tpl, encoding="utf-8").read()
for k in ("FEATURE","SLUG","DATE","SUMMARY"):
    v = os.environ.get(k, "")
    if k == "SUMMARY" and not v:
        v = "TODO: one-line problem statement"
    text = text.replace("{{%s}}" % k, v)
open(dest, "w", encoding="utf-8").write(text)
PY
}

cmd_new(){
  local name="${1:-}"; [ -n "$name" ] || die "usage: flow new <feature> [\"one-line problem\"]"
  local s; s="$(slug "$name")"; [ -n "$s" ] || die "bad feature name"
  local d="$FEAT/$s"; mkdir -p "$d"
  [ -f "$d/intent.md" ] && die "$s already exists ($d/intent.md)"
  scaffold "$TPL/intent.md" "$d/intent.md" "$name" "$s" "${2:-}"
  printf '%screated%s %s\n' "$c_grn" "$c_0" "docs/features/$s/intent.md"
  printf '  fill in the Problem/Outcome, then: %sflow next %s%s\n' "$c_cy" "$s" "$c_0"
}

cmd_next(){
  local s; s="$(slug "${1:-}")"; [ -n "$s" ] || die "usage: flow next <feature>"
  local d="$FEAT/$s"; [ -d "$d" ] || die "no such feature '$s' (try: flow new $s)"
  local feature; feature="$(sed -n 's/^# Intent — //p' "$d/intent.md" 2>/dev/null)"; feature="${feature:-$s}"
  if [ ! -f "$d/spec.md" ]; then
    scaffold "$TPL/spec.md" "$d/spec.md" "$feature" "$s"
    printf '%s→ Design.%s wrote %s — fill it from intent.md, then: %sflow next %s%s\n' \
      "$c_grn" "$c_0" "docs/features/$s/spec.md" "$c_cy" "$s" "$c_0"
  elif [ ! -f "$d/plan.md" ]; then
    scaffold "$TPL/plan.md" "$d/plan.md" "$feature" "$s"
    printf '%s→ Build.%s wrote %s — write the plan, get it approved, then implement.\n' \
      "$c_grn" "$c_0" "docs/features/$s/plan.md"
    printf '  when code is done: %sflow test%s then %sflow ship %s%s\n' "$c_cy" "$c_0" "$c_cy" "$s" "$c_0"
  else
    printf 'plan.md already exists. Implement it, then: %sflow test && flow ship %s%s\n' "$c_cy" "$s" "$c_0"
  fi
}

stage_of(){  # prints a compact stage string for a feature dir
  local d="$1" m=""
  [ -f "$d/intent.md" ] && m="${m}intent " || m="${m}·      "
  [ -f "$d/spec.md" ]   && m="${m}spec " || m="${m}·    "
  [ -f "$d/plan.md" ]   && m="${m}plan " || m="${m}·    "
  [ -f "$d/.shipped" ]  && m="${m}${c_grn}shipped${c_0}" || m="${m}${c_dim}building${c_0}"
  printf '%s' "$m"
}

cmd_status(){
  [ -d "$FEAT" ] || { echo "no features yet — start one with: flow new <feature>"; return 0; }
  local one="${1:-}"
  printf '%s%-30s %s%s\n' "$c_dim" "FEATURE" "intent spec plan   state" "$c_0"
  local d s
  for d in "$FEAT"/*/; do
    [ -d "$d" ] || continue
    s="$(basename "$d")"
    [ -n "$one" ] && [ "$s" != "$(slug "$one")" ] && continue
    printf '%-30s %s\n' "$s" "$(stage_of "${d%/}")"
  done
}

cmd_test(){
  cd "$ROOT"
  printf '%srunning checks…%s\n' "$c_dim" "$c_0"
  "$PY" -m pytest -q
}

cmd_ship(){
  local s; s="$(slug "${1:-}")"; [ -n "$s" ] || die "usage: flow ship <feature>"
  local d="$FEAT/$s"; [ -d "$d" ] || die "no such feature '$s'"
  cd "$ROOT"
  cmd_test
  : > "$d/.shipped"
  printf '%s✓ checks passed.%s marked %s shipped.\n' "$c_grn" "$c_0" "$s"
  echo "--- diff since last commit ---"
  git -C "$ROOT" diff --stat 2>/dev/null || true
  printf 'Review the diff, then commit + push yourself (human approves the ship).\n'
}

case "${1:-help}" in
  new)    shift; cmd_new "$@";;
  next)   shift; cmd_next "$@";;
  status) shift; cmd_status "$@";;
  test)   shift; cmd_test "$@";;
  ship)   shift; cmd_ship "$@";;
  help|-h|--help) sed -n '2,12p' "$0" | sed 's/^# \{0,1\}//';;
  *) die "unknown command '${1}'. Try: flow help";;
esac
