#!/usr/bin/env bash
# Scaffold a machine-discovery F1 project workspace. Idempotent.
# Usage: discovery-init.sh <project-slug>
set -euo pipefail

SLUG="${1:-}"

if [ -z "$SLUG" ]; then
  echo "ERROR: project slug required, e.g. discovery-init.sh acme-demo" >&2
  exit 2
fi
if ! printf '%s' "$SLUG" | grep -Eq '^[a-z0-9]+(-[a-z0-9]+)*$'; then
  echo "ERROR: slug must be kebab-case ASCII (lowercase letters, numbers, single hyphens): $SLUG" >&2
  exit 2
fi

INPUTS_DIR="docs/inputs/$SLUG"
DISC_DIR="docs/discovery/$SLUG"

DIRS=(
  "$INPUTS_DIR/raw"
  "$INPUTS_DIR/transcriptions"
  "$DISC_DIR/inputs"
  "$DISC_DIR/requirements"
  "$DISC_DIR/requirements/items"
  "$DISC_DIR/hla"
  "$DISC_DIR/planning"
  "$DISC_DIR/draft-prds"
  "$DISC_DIR/draft-prds/items"
  "$DISC_DIR/project-doc"
  "$DISC_DIR/commercial-offer"
)

for d in "${DIRS[@]}"; do
  if [ -d "$d" ]; then echo "exists dir:    $d"; else mkdir -p "$d"; echo "created dir:   $d"; fi
done

write_index() {
  local path="$1" key="$2"
  if [ -f "$path" ]; then
    echo "exists index:  $path"
  else
    printf '{\n  "project": "%s",\n  "%s": []\n}\n' "$SLUG" "$key" > "$path"
    echo "created index: $path"
  fi
}

write_index "$INPUTS_DIR/index.json" "inputs"
write_index "$DISC_DIR/requirements/index.json" "requirements"
write_index "$DISC_DIR/draft-prds/index.json" "prds"

PROP_SRC="docs/business/$SLUG/proposal.md"
PROP_DST="$DISC_DIR/inputs/business-proposal.md"
if [ -f "$PROP_DST" ]; then
  echo "exists proposal: $PROP_DST"
elif [ -f "$PROP_SRC" ]; then
  cp "$PROP_SRC" "$PROP_DST"
  echo "copied proposal: $PROP_SRC -> $PROP_DST"
else
  echo "no proposal: place your business proposal at $PROP_DST"
fi

missing=0
for p in "${DIRS[@]}" \
  "$INPUTS_DIR/index.json" \
  "$DISC_DIR/requirements/index.json" \
  "$DISC_DIR/draft-prds/index.json"; do
  if [ ! -e "$p" ]; then echo "ERROR: expected path missing after init: $p" >&2; missing=1; fi
done
[ "$missing" -eq 0 ] || exit 1

if [ -n "$(ls -A "$INPUTS_DIR/raw" 2>/dev/null)" ]; then
  echo "NEXT_COMMAND=/machine-discovery:process-input $SLUG"
else
  echo "NEXT_COMMAND=/machine-discovery:requirements $SLUG"
fi

echo "OK: discovery workspace ready for $SLUG"
