#!/usr/bin/env bash
# EZZIE · PHI · THERMO cook · language + vocab from Desktop/x
# think · secure · save · cook · <3 · one-shot (NOT always thrash)
# Law: BGS → BGF(+EZZIE PHI THERMO) → BGL secure/clean → SDF · SPV free
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT="$ROOT/out"
mkdir -p "$OUT"
export SUDO_PASS="${SUDO_PASS:-mememe}"
export DISPLAY="${DISPLAY:-:0}"
export BGL_SKIP_SCAN="${BGL_SKIP_SCAN:-1}"
TS=$(date +%Y%m%d-%H%M%S)
LOG="$OUT/ept-cook-$TS.txt"
SAVE="$OUT/ept_cook_save.json"
SHEET="$OUT/EPT_COOK_SHEET.txt"

say() { echo "$*" | tee -a "$LOG"; }

ezzie() { echo $(( ($1 ^ $2) | 1 )); }
phi()   { echo $(( ($1 * $2) | 1 )); }
thermo() {
  local t=$1
  if (( t <= 70 )); then echo $((0 | 1))
  elif (( t <= 84 )); then echo $((1 | 1))
  else echo $((2 | 1)); fi
}
bgf() { echo $(( ($1 - $2) | 1 )); }
bgl() { echo $(( ${1:-0} | 1 )); }
spv() { echo $(( (${1:-0} ^ ${2:-0} ^ ${3:-0}) | 1 )); }

say "############################################"
say "# EZZIE · PHI · THERMO COOK · LANGUAGE · VOCAB"
say "# think · secure · save · cook · <3"
say "# $(date -Iseconds)"
say "############################################"
say "LINEAR: BGS ground → BGF measure(+EZZIE PHI THERMO) → BGL secure → SDF · SPV free"
say "ESSIE=hotswap · EZZIE=free eor · never mix · never fold free SPV into SDF"

# --- THINK · harvest Desktop/x language + vocab ---
say "=== THINK · Desktop/x language + vocab limbs ==="
VOCAB_LIST="$OUT/desktop_x_vocab_limbs.txt"
find "$ROOT" -maxdepth 2 -name 'x86_64.asm' 2>/dev/null | sort | while read -r f; do
  d=$(basename "$(dirname "$f")")
  head1=$(head -1 "$f" 2>/dev/null | sed 's/^; *//')
  echo -e "${d}\t${head1}"
done >"$VOCAB_LIST"
n_limbs=$(wc -l <"$VOCAB_LIST" | tr -d ' ')
say "vocab_limbs=$n_limbs  sheet=$VOCAB_LIST"

# thinking tokens from desk law language (not /usr haul)
THINK_TOKENS="$OUT/desktop_x_think_tokens.txt"
{
  # pin words
  echo "BGS BGF BGL SDF SPV EZZIE PHI THERMO ESSIE EKKIE H7 GRIN STONE"
  echo "think secure save cook grease reinstant measure ground place free fold"
  echo "field_one know_her axle bearings TX RX TRUTH Hostess7 never_fold"
  echo "inject PRIMARY CLIPBOARD xdg-open virus datacenter 127 Atomic"
  # first word of every limb name = desk vocab
  awk -F'\t' '{print $1}' "$VOCAB_LIST"
  # STONE names
  awk '/^  [A-Z][A-Z0-9_]+/{print $1}' "$ROOT/RTXLayer/webbrowser/STONE-SDF-VOCAB.txt" 2>/dev/null || true
  # HINTS content words
  tr -cs 'A-Za-z0-9_.' '\n' <"$ROOT/HINTS.txt" 2>/dev/null | awk 'length>=3' || true
} | tr ' ' '\n' | sed '/^$/d' | sort -u >"$THINK_TOKENS"
n_tok=$(wc -l <"$THINK_TOKENS" | tr -d ' ')
say "think_tokens=$n_tok  (unique desk language · not /usr dict haul)"

# language sheet for save
{
  echo "EPT COOK LANGUAGE SHEET · $(date -Iseconds)"
  echo "============================================"
  echo "LAW: BGS → BGF(+EZZIE PHI THERMO) → BGL → SDF · SPV free · <3"
  echo
  echo "--- ATOMS (ride BGF · still linear · not side engines) ---"
  echo "EZZIE  (a^b)|1  free eor electric · limb ezzie/x86_64.asm · != ESSIE"
  echo "PHI    (d*s)|1  scale mul · limb phi/x86_64.asm"
  echo "THERMO band|1   cool<=70 warm<=84 hot · limb thermo/x86_64.asm"
  echo
  echo "--- THINK / SECURE / SAVE / COOK words ---"
  echo "think  = measure first · limbs + tokens · no /usr inject"
  echo "secure = BGL · inject guard · 127 · 0 public · no xdg-open"
  echo "save   = out/ept_cook_save.json · sheet · vocab limbs · STAY"
  echo "cook   = one-shot reinstant + full · NEVER always thrash"
  echo
  head -5 "$ROOT/HINTS.txt" 2>/dev/null
  echo
  echo "--- VOCAB LIMBS ($n_limbs) sample ---"
  head -40 "$VOCAB_LIST"
  echo "..."
  echo "--- THINK TOKENS sample ---"
  head -60 "$THINK_TOKENS"
} >"$SHEET"
say "language_sheet=$SHEET"

# --- BGS ground ---
say "=== BGS GROUND ==="
bash "$ROOT/Build/cover.sh" bgs >>"$LOG" 2>&1 || true

# --- ATOMS on BGF ---
say "=== ATOMS · EZZIE · PHI · THERMO ==="
bash "$ROOT/Build/cover.sh" atoms >>"$LOG" 2>&1 || true
mf=$(awk '/^MemFree:/{print $2;exit}' /proc/meminfo)
mc=$(awk '/^Cached:/{print $2;exit}' /proc/meminfo)
mhz=$(awk '/^cpu MHz/{print int($4); exit}' /proc/cpuinfo 2>/dev/null || echo 0)
tC=27
if [[ -r /sys/class/thermal/thermal_zone0/temp ]]; then
  tC=$(( $(cat /sys/class/thermal/thermal_zone0/temp) / 1000 ))
fi
# some boards use hwmon
if [[ -d /sys/class/hwmon ]]; then
  for t in /sys/class/hwmon/hwmon*/temp*_input; do
    [[ -r "$t" ]] || continue
    v=$(( $(cat "$t") / 1000 ))
    (( v > 0 && v < 120 )) && tC=$v && break
  done
fi
m=$(bgf "$mf" "$mc")
at_ez=$(ezzie "$m" "$mhz")
at_phi=$(phi "$m" 1)
at_th=$(thermo "$tC")
# language-scaled atoms: xor token count into eor lane (still |1)
at_ez_lang=$(ezzie "$at_ez" "$n_tok")
at_phi_lang=$(phi "$n_limbs" 1)
at_th_lang=$(thermo "$tC")
free_spv=$(spv "$at_ez" "$at_phi" "$at_th")
say "BGF measure free_vs_cache=$m  MemFree=$mf Cached=$mc temp_C=$tC mhz=$mhz"
say "EZZIE electric=$at_ez  +lang_eor=$at_ez_lang  limb=ezzie/"
say "PHI    scale=$at_phi  limbs_scale=$at_phi_lang  limb=phi/  vocab_limbs=$n_limbs"
say "THERMO heat=$at_th  band|1 cool/warm/hot  limb=thermo/  temp_C=$tC"
say "SPV free mix=$free_spv  (rides · never folds)"

# --- TX/RX wire ---
say "=== TX/RX · wire on BGS field ==="
bash "$ROOT/Build/cover.sh" tx-rx >>"$LOG" 2>&1 || true

# --- COOK · one-shot reinstant (grease all bearings) ---
say "=== COOK · BGF reinstant ALL bearings · axle grease · NO KIDDING ==="
bash "$ROOT/Build/cover.sh" reinstant >>"$LOG" 2>&1 || true

# --- COOK · full system one-shot ---
say "=== COOK · full system one-shot (not always) ==="
bash "$ROOT/Build/cover.sh" full >>"$LOG" 2>&1 || true

# --- SECURE · BGL + inject guard ---
say "=== SECURE · BGL clean all surfaces + text inject guard ==="
bash "$ROOT/Build/bgl-secure.sh" >>"$LOG" 2>&1 || true
bash "$ROOT/Build/av-inject-guard.sh" >>"$LOG" 2>&1 || true

# re-measure after cook/secure
mf2=$(awk '/^MemFree:/{print $2;exit}' /proc/meminfo)
mc2=$(awk '/^Cached:/{print $2;exit}' /proc/meminfo)
tC2=$tC
if [[ -r /sys/class/thermal/thermal_zone0/temp ]]; then
  tC2=$(( $(cat /sys/class/thermal/thermal_zone0/temp) / 1000 ))
fi
m2=$(bgf "$mf2" "$mc2")
at_ez2=$(ezzie "$m2" "$mhz")
at_phi2=$(phi "$m2" 1)
at_th2=$(thermo "$tC2")
free_spv2=$(spv "$at_ez2" "$at_phi2" "$at_th2")
pub=$(ss -ltn 2>/dev/null | awk 'NR>1 && $4 !~ /127\.|::1/ {c++} END{print c+0}')
dc=$(systemctl is-active bgrtx-datacenter.service 2>/dev/null || echo dead)
ok=$(systemctl is-active grok-orphan-kill.timer 2>/dev/null || echo dead)

say "=== AFTER COOK · measure again ==="
say "BGF=$m2  EZZIE=$at_ez2  PHI=$at_phi2  THERMO=$at_th2  SPV_free=$free_spv2"
say "public_listen=$pub  datacenter=$dc  orphan_timer=$ok  BGL_public_quiet=$(bgl $((pub==0?1:0)))"

# --- SAVE ---
say "=== SAVE · ept cook artifacts ==="
cat >"$SAVE" <<JSON
{
  "law": "BGS → BGF(+EZZIE PHI THERMO) → BGL secure/clean → SDF · SPV free · never fold",
  "heart": "<3",
  "mode": "one-shot cook · not always thrash",
  "ts": "$(date -Iseconds)",
  "think": {
    "vocab_limbs": $n_limbs,
    "think_tokens": $n_tok,
    "vocab_list": "out/desktop_x_vocab_limbs.txt",
    "tokens": "out/desktop_x_think_tokens.txt",
    "language_sheet": "out/EPT_COOK_SHEET.txt",
    "stone": "RTXLayer/webbrowser/STONE-SDF-VOCAB.txt",
    "hints": "HINTS.txt"
  },
  "atoms_before": {
    "EZZIE": {"law": "(a^b)|1 free eor", "value": $at_ez, "lang_eor": $at_ez_lang},
    "PHI":   {"law": "(d*s)|1 scale", "value": $at_phi, "limbs_scale": $at_phi_lang},
    "THERMO":{"law": "band|1 cool<=70 warm<=84 hot", "value": $at_th, "temp_C": $tC}
  },
  "atoms_after": {
    "EZZIE": $at_ez2,
    "PHI": $at_phi2,
    "THERMO": $at_th2,
    "temp_C": $tC2,
    "SPV_free": $free_spv2
  },
  "bgf": {
    "before": $m,
    "after": $m2,
    "mem_free_kb": $mf2,
    "cached_kb": $mc2
  },
  "secure": {
    "public_listen": $pub,
    "public_quiet": $((pub==0?1:0)),
    "datacenter": "$dc",
    "orphan_timer": "$ok",
    "inject": "out/NO_INJECT",
    "bgl": "out/bgl_secure.json"
  },
  "cook": ["bgs", "atoms", "tx-rx", "reinstant", "full", "bgl-secure", "av-inject"],
  "log": "$LOG",
  "remain": "IN"
}
JSON
cp -f "$SAVE" "$OUT/ept_cook_latest.json"
echo "COOK $(date -Iseconds) EZZIE=$at_ez2 PHI=$at_phi2 THERMO=$at_th2 SPV=$free_spv2 limbs=$n_limbs tokens=$n_tok <3" >"$OUT/EPT_COOKED"
# stamp stay clean without always loop
echo "CLEAN $(date -Iseconds) ept-cook limbs=$n_limbs" >"$OUT/STAY_CLEAN"

say "wrote $SAVE"
say "wrote $OUT/EPT_COOKED"
say "############################################"
say "# EPT COOK DONE · think secure save cook · <3"
say "# EZZIE=$at_ez2 PHI=$at_phi2 THERMO=$at_th2 SPV_free=$free_spv2"
say "# vocab_limbs=$n_limbs think_tokens=$n_tok"
say "############################################"
echo "$LOG"
