#!/bin/bash
# full language learning · ASM only outputs · EKKIE center
set -e
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
LIMBS="$ROOT/spine/LIMBS.asm"
OUT="$ROOT/out"
BUILD="$ROOT/Build"
mkdir -p "$OUT"

order="$ROOT/spine/ORDER.asm"
sheet="$OUT/learn_sheet.asm"
report="$OUT/learn_report.asm"

n=0; ok=0; miss=0; noret=0

{
  echo "; LEARN REPORT · pure ASM · $(date -Iseconds)"
  echo "; EKKIE center · no md · no txt"
  echo
  echo "; scraps follow as comment census then PATH bodies in learn_sheet.asm"
  echo
} > "$report"

{
  echo "; ORDER · learned PATH · EKKIE first among fields"
  echo
} > "$order"

{
  echo "; learn_sheet · full language · every scrap body"
  echo "; EKKIE = local NOW field everywhere"
  echo
} > "$sheet"

while IFS= read -r line; do
  if [[ "$line" =~ ^\;\ === ]]; then
    echo "$line" >> "$order"
    echo "$line" >> "$sheet"
    echo "$line" >> "$report"
    continue
  fi
  [[ "$line" =~ ^PATH: ]] || continue
  p="${line#PATH: }"; p="${p//$'\r'/}"
  name="${p%/x86_64.asm}"
  n=$((n+1))
  if [ ! -f "$ROOT/$p" ]; then
    echo "; MISS $name" >> "$report"
    miss=$((miss+1))
    continue
  fi
  ok=$((ok+1))
  sense=$(grep -m1 '^;' "$ROOT/$p" | sed 's/^; *//')
  if ! grep -qE '^[[:space:]]*ret[[:space:]]*$' "$ROOT/$p"; then
    noret=$((noret+1)); rm="NO_RET"
  else rm="ret"; fi
  echo "; LEARN $name · $rm · $sense" >> "$report"
  echo "PATH: $p" >> "$order"
  {
    echo "; === LEARN $name · $rm ==="
    echo "; $sense"
    cat "$ROOT/$p"
    echo
  } >> "$sheet"
done < "$LIMBS"

{
  echo
  echo "; CENSUS scraps_ok=$ok miss=$miss total=$n noret=$noret"
  echo "; dict_corpus lines=$(wc -l < "$BUILD/dict_corpus.asm" 2>/dev/null || echo 0)"
  echo "; thesaurus_bridges present"
  echo "; LEARN COMPLETE · we_know · EKKIE"
  echo "        mov     eax, $ok"
  echo "        or      eax, 1"
  echo "        ret"
} >> "$report"

# iron test
if [ -f "$BUILD/test.asm" ]; then
  nasm -f elf64 -o "$BUILD/test.o" "$BUILD/test.asm"
  ld -o "$BUILD/test" "$BUILD/test.o"
  "$BUILD/test" || true
fi

echo "LEARN ok=$ok miss=$miss noret=$noret"
echo "wrote $report"
echo "wrote $order"
echo "wrote $sheet ($(wc -l < "$sheet") lines)"
