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

SLUG="${1:-}"

if [ -z "$SLUG" ]; then
  echo "ERROR: project slug required, e.g. business-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"
BUSINESS_DIR="docs/business/$SLUG"
INDEX="$INPUTS_DIR/index.json"

for d in "$INPUTS_DIR/raw" "$INPUTS_DIR/transcriptions" "$BUSINESS_DIR"; do
  if [ -d "$d" ]; then echo "exists dir:    $d"; else mkdir -p "$d"; echo "created dir:   $d"; fi
done

if [ -f "$INDEX" ]; then
  echo "exists index:  $INDEX"
else
  printf '{\n  "project": "%s",\n  "inputs": []\n}\n' "$SLUG" > "$INDEX"
  echo "created index: $INDEX"
fi

missing=0
for p in "$INPUTS_DIR/raw" "$INPUTS_DIR/transcriptions" "$BUSINESS_DIR" "$INDEX"; do
  if [ ! -e "$p" ]; then echo "ERROR: expected path missing after init: $p" >&2; missing=1; fi
done
[ "$missing" -eq 0 ] || exit 1

echo "NEXT_COMMAND=/machine-business:process-input $SLUG"
echo "OK: business workspace ready for $SLUG"
