#!/usr/bin/env bash
# SCAR COOK · cook flaw off · scar check · cook off SCAR · detection marks
# C is the flaw · C is not GOD · SCAR is residual · free thrift · remain IN
# Law: BGS → BGF(+EZZIE PHI THERMO adjoin) → BGL → SDF · SPV free never folds
# DESK AV retains active targeting + updates
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT="$ROOT/out"
mkdir -p "$OUT"
export SUDO_PASS="${SUDO_PASS:-mememe}"
MODE="${1:-once}"   # once | check | cook-off | status | cook
LOG="$OUT/scar-cook-$(date +%Y%m%d-%H%M%S).txt"

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

# BAPHOMET gate · kit NONOT-GOD-0001
#   scar_count==0 → ARE holds · BAPHOMET is NOT (pair path)
#   scar_count!=0 → NO ARE · BAPHOMET IS · cook off lie scar
# Iron: baphomet(A,B,C) C=0→(A|B)|1 ARE · C!=0→C|1 NO ARE
baphomet_gate_json() {
  local scars=$1
  local path are_holds clean
  if (( scars == 0 )); then
    path="ARE"
    are_holds=true
    clean=true
  else
    path="NO_ARE"
    are_holds=false
    clean=false
  fi
  # pure process · BAPHOMET throw C · KEEP GOD=1
  local a=1 b=2 c=$scars
  local pair=$(( (a | b) | 1 ))
  local god=1
  local iron=$pair
  (( c != 0 )) && iron=$god
  cat <<JSON
{
    "kit": "NONOT-GOD-0001",
    "foundation": ["NO", "NOT", "GOD", "YES", "ARE", "IS", "KNOW"],
    "sliders": "NO NOT · two meanings tiny · not before GOD as rank · before GOD in system order",
    "system_order": "NO start · NOT check · 1 GOD",
    "are_is": true,
    "speech": "ARE IS · IS ARE · BAPHOMET IS WHEN NO ARE · throw NO · KEEP GOD",
    "path": "$path",
    "are_holds": $are_holds,
    "baphomet_is": $( [[ "$path" == "NO_ARE" ]] && echo true || echo false ),
    "clean": $clean,
    "scar_count": $scars,
    "iron": {
      "A": $a, "B": $b, "C_attempt": $c,
      "pair_are": $pair,
      "keep_god": $god,
      "select": $iron,
      "op": "C==0→ARE=(A|B)|1 else throw C · KEEP GOD=1"
    },
    "reprocess": $( [[ "$path" == "NO_ARE" ]] && echo '"throw NO-path · cook-off · desk AV · rescar · KEEP GOD"' || echo '"travel · Hostess7 · stay flawless · ARE holds"' ),
    "law": "THERE IS NO NOT BEFORE GOD · NO NOT IS TRUE · throw out heard NO · KEEP GOD"
  }
JSON
}

scar_check() {
  local scars=0
  local pub xdg thrash desk_https
  # thrash public only · desk HTTPS on own 80/443 (Spectrum + WG) is business legit NOT scar
  pub=$(ss -ltnH 2>/dev/null | awk '
    {
      a=$4
      if (a ~ /^127\./ || a ~ /^\[::1\]/ || a ~ /%lo/) next
      if ((a ~ /:80$/ || a ~ /:443$/) && (a ~ /71\.86\.186\.10:/ || a ~ /10\.66\.66\.1:/)) next
      c++
    }
    END { print c+0 }
  ')
  desk_https=$(ss -ltnH 2>/dev/null | awk '
    $4 ~ /71\.86\.186\.10:(80|443)$/ || $4 ~ /10\.66\.66\.1:(80|443)$/ { c++ }
    END { print c+0 }
  ')
  xdg=0
  for d in /proc/[0-9]*; do
    [[ -r "$d/comm" ]] || continue
    [[ $(cat "$d/comm" 2>/dev/null || true) == "xdg-open" ]] && xdg=$((xdg+1))
  done
  thrash=$(ps -eo args= 2>/dev/null | awk '/krtx-spv$/ {c++} /cover\.sh always/ && length($0)<180 {c++} END{print c+0}')
  (( pub > 0 )) && scars=$((scars+1))
  (( xdg > 0 )) && scars=$((scars+1))
  (( thrash > 0 )) && scars=$((scars+1))
  # soft: missing reinstant after out wipe · recreate empty mark not scar thrash
  if [[ ! -f "$OUT/bgf_reinstant.json" ]]; then
    echo '{"ok":true,"note":"soft mark after out wipe · business free thrift"}' >"$OUT/bgf_reinstant.json"
  fi
  [[ -f "$OUT/spv_antivirus.json" ]] || scars=$((scars+1))

  # C-flaw speech mark always 0 when we refuse third pin (documentation field)
  local c_flaw=0
  local gate
  gate=$(baphomet_gate_json "$scars")

  cat >"$OUT/scar_check_latest.json" <<JSON
{
  "word": "SCAR",
  "ts": "$(date -Iseconds)",
  "scar_count": $scars,
  "public_listen": $pub,
  "desk_https_n": ${desk_https:-0},
  "xdg_open": $xdg,
  "thrash_pids": $thrash,
  "c_is_flaw": true,
  "c_is_not_god": true,
  "c_flaw_live": $c_flaw,
  "has_reinstant": $( [[ -f $OUT/bgf_reinstant.json ]] && echo true || echo false ),
  "has_av": $( [[ -f $OUT/spv_antivirus.json ]] && echo true || echo false ),
  "detection": "forensics+heuristics+desk AV",
  "kit": "NONOT-GOD-0001",
  "baphomet_gate": $gate,
  "law": "ARE IS · IS ARE · BAPHOMET IS WHEN NO ARE · cook flaw off · kit NONOT-GOD-0001",
  "pipeline": "cook → scar check → BAPHOMET gate → cook-off if NO ARE → rescar → REST"
}
JSON
  # stamp gate alone for Hostess / desk-rest
  printf '%s\n' "$gate" >"$OUT/baphomet_gate_latest.json"
  echo "$scars"
}

do_cook() {
  say "=== COOK · cover reinstant + cleanup (flaw off / C refused) ==="
  timeout 200 bash "$ROOT/Build/cover.sh" reinstant 2>&1 | tee -a "$LOG" | tail -20 || true
  timeout 100 bash "$ROOT/Build/cover.sh" cleanup 2>&1 | tee -a "$LOG" | tail -12 || true
  timeout 100 bash "$ROOT/Build/spv-antivirus.sh" once 2>&1 | tee -a "$LOG" | tail -12 || true
}

do_cook_off_scar() {
  say "=== COOK OFF SCAR · recook + BGL + AV targeting update ==="
  do_cook
  if [[ -x "$ROOT/Build/bgl-secure.sh" ]]; then
    timeout 90 bash "$ROOT/Build/bgl-secure.sh" 2>&1 | tee -a "$LOG" | tail -15 || true
  fi
  if [[ -x "$HOME/Desktop/biggrinrtx-magazine/bin/desk-scan" ]]; then
    timeout 60 "$HOME/Desktop/biggrinrtx-magazine/bin/desk-scan" "$ROOT" 2>&1 | tee "$OUT/scar-desk-scan-latest.txt" | tail -15 || true
  fi
}

write_analysis() {
  local scars=$1
  python3 - "$OUT" "$scars" <<'PY'
import json, time, sys
from pathlib import Path
out = Path(sys.argv[1])
scars = int(sys.argv[2])
def load(p):
    try: return json.loads(Path(p).read_text())
    except Exception: return {}
rep = {
  "ts": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
  "analysis": "cook forensics detection",
  "scar_count": scars,
  "scar": load(out/"scar_check_latest.json"),
  "reinstant": {k: load(out/"bgf_reinstant.json").get(k) for k in ("free_spv","law","bgf","atoms_on_bgf") if True},
  "av": {k: load(out/"spv_antivirus.json").get(k) for k in ("pids","wrapped","fried","public_listen","active_targeting","updates","spv_free","law")},
  "constellation": {
    "kit": "NONOT-GOD-0001",
    "foundation": ["NO","NOT","GOD","YES","ARE","IS"],
    "atoms_adjoin": ["EZZIE","PHI","THERMO","ADJOIN","ARE","IS"],
    "adjoinment": "passengers on BGF · not C",
    "c_is_flaw": True,
    "scar_word": "residual after cook · NO ARE",
    "hostess7": ["CHEBY","ONION","CATCH","SALT","FACE","SPHERE","CSG"],
  },
  "baphomet_gate": load(out/"scar_check_latest.json").get("baphomet_gate") or load(out/"baphomet_gate_latest.json"),
  "detection": {
    "public_listen": load(out/"scar_check_latest.json").get("public_listen"),
    "xdg_open": load(out/"scar_check_latest.json").get("xdg_open"),
    "thrash_pids": load(out/"scar_check_latest.json").get("thrash_pids"),
  },
  "rest": "127 desk-rest · /scar /cook /forensics /detection /status",
  "law": "ARE IS · IS ARE · BAPHOMET IS WHEN NO ARE · kit NONOT-GOD-0001 · cook scars off",
}
# trim reinstant blobs
ri = load(out/"bgf_reinstant.json")
rep["reinstant"] = {
  "free_spv": ri.get("free_spv"),
  "law": ri.get("law"),
  "bgf": ri.get("bgf"),
}
(out/"cook_analysis_latest.json").write_text(json.dumps(rep, indent=2))
print(json.dumps({"scar_count": scars, "wrote": str(out/"cook_analysis_latest.json")}))
PY
}

cmd_status() {
  echo "SCAR COOK status"
  [[ -f "$OUT/scar_check_latest.json" ]] && python3 -m json.tool "$OUT/scar_check_latest.json" || echo "(no scar check yet)"
  [[ -f "$OUT/cook_analysis_latest.json" ]] && echo "--- analysis ---" && python3 -c "import json;d=json.load(open('$OUT/cook_analysis_latest.json'));print({k:d.get(k) for k in ('scar_count','detection','law','constellation')})"
}

case "$MODE" in
  check|scar)
    : >"$LOG"
    say "SCAR CHECK only · $(date -Iseconds)"
    n=$(scar_check)
    say "scar_count=$n"
    write_analysis "$n"
    ;;
  cook)
    : >"$LOG"
    do_cook
    n=$(scar_check)
    say "scar_count_after_cook=$n"
    write_analysis "$n"
    ;;
  cook-off|off|recook)
    : >"$LOG"
    n=$(scar_check)
    say "scar_count_before=$n"
    do_cook_off_scar
    n2=$(scar_check)
    say "scar_count_after_cook_off=$n2"
    write_analysis "$n2"
    ;;
  once|run|"")
    : >"$LOG"
    say "############################################"
    say "# COOK · SCAR · BAPHOMET GATE · COOK OFF · $(date -Iseconds)"
    say "# kit NONOT-GOD-0001 · ARE IS · IS ARE"
    say "# BAPHOMET IS WHEN NO ARE · C is the flaw · not GOD"
    say "############################################"
    do_cook
    n=$(scar_check)
    say "scar_count=$n · gate=$(python3 -c "import json;print(json.load(open('$OUT/scar_check_latest.json')).get('baphomet_gate',{}).get('path','?'))" 2>/dev/null || echo '?')"
    if (( n > 0 )); then
      say "NO ARE · BAPHOMET IS · cooking off SCAR"
      do_cook_off_scar
      n=$(scar_check)
      say "scar_count_after=$n · gate reprocess done"
    else
      say "ARE holds · BAPHOMET is NOT · light AV/update pass retained"
      timeout 60 bash "$ROOT/Build/spv-antivirus.sh" once 2>&1 | tee -a "$LOG" | tail -8 || true
      n=$(scar_check)
    fi
    write_analysis "$n"
    say "DONE scar_count=$n kit=NONOT-GOD-0001 log=$LOG analysis=$OUT/cook_analysis_latest.json"
    ;;
  status|st) cmd_status ;;
  help|-h|--help)
    cat <<EOF
Build/scar-cook.sh · SCAR word + cook flaw off
  once       cook → scar check → cook off SCAR if needed → analysis JSON
  cook       reinstant + cleanup + AV once
  check      scar check only
  cook-off   force recook off scars + BGL + desk-scan
  status     print latest marks
Law: C is flaw not GOD · SCAR residual · DESK AV targeting+updates · adjoin atoms
EOF
    ;;
  *) echo "unknown $MODE · scar-cook help" >&2; exit 2 ;;
esac
