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

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
ROOT="${PROJECT_ROOT:-$(git -C "$SCRIPT_DIR" rev-parse --show-toplevel 2>/dev/null || pwd)}"

ART="$ROOT/.mbs_artifacts"
LIST="$ART/blade_files.txt"
DONE="$ART/done.txt"
VIEWS_DIR="$ROOT/resources/views"
HASH="$SCRIPT_DIR/_hash.sh"
PROMPT_PATH="${PROMPT_PATH:-$SCRIPT_DIR/blade-metaprompt.txt}"

[ -f "$LIST" ] || { echo "Run $SCRIPT_DIR/blade-queue-init.sh first."; exit 1; }
[ -f "$DONE" ] || touch "$DONE"
[ -f "$PROMPT_PATH" ] || { echo "Missing metaprompt at $PROMPT_PATH"; exit 1; }

# Load "done" keys (supports lines: 'HASH path' or just 'path')
declare -A DONE_SET
while IFS= read -r line; do
  [[ -z "$line" ]] && continue
  DONE_SET["$line"]=1
done < <(grep -v '^[[:space:]]*$' "$DONE" 2>/dev/null || true)

while IFS= read -r rel; do
  [[ -z "$rel" ]] && continue
  fp="$VIEWS_DIR/$rel"
  [ -f "$fp" ] || continue

  file_hash="$("$HASH" hash_file "$fp")"
  key1="$file_hash $rel"
  key2="$rel"

  if [[ -n "${DONE_SET[$key1]:-}" || -n "${DONE_SET[$key2]:-}" ]]; then
    continue
  fi

  echo "=== NEXT TASK ==="
  echo "FILE: resources/views/$rel"
  echo "HASH: $file_hash"
  echo
  echo "INSTRUCTIONS:"
  echo "1) Use the metaprompt at: $PROMPT_PATH"
  echo "2) Analyze the file below (full contents included)."
  echo "3) Produce JSON + a ≤12-line Markdown summary."
  echo "4) Append the Markdown summary to MBS_BLADE_discovery.md."
  echo "5) Optionally save the full LLM output to .mbs_artifacts/cache/${rel//\//__}.md"
  echo "6) When satisfied, mark done:"
  echo "   $SCRIPT_DIR/blade-done.sh \"resources/views/$rel\" \"$file_hash\""
  echo
  echo "----- BEGIN PROMPT (copy/paste into your LLM) -----"
  echo "SYSTEM (from $PROMPT_PATH):"
  echo '```'
  cat "$PROMPT_PATH"
  echo '```'
  echo
  echo "USER:"
  echo '```'
  echo "file_path: resources/views/$rel"
  echo "source:"
  echo '```blade'
  cat "$fp"
  echo '```'
  echo '```'
  echo "----- END PROMPT -----"
  exit 0
done < "$LIST"

echo "No pending files. All done or list empty."
