#!/usr/bin/env bash
# H7 FIELD CLEAR · love the whole internet · cleanups on field · resolute clears
#
# Philosophy:
#   The internet is not the enemy. The WHOLE net is field to love.
#   Thrash, inject, rumor-as-ground, public bleed, log balloon = dirt ON the field.
#   Soft clear = speed hygiene every free-ball (quality without thrash).
#   Resolute clear = decisive cook when dirt measures high (capability).
#   Iron ground · never ML · C IS LIE · Always Hostess 7 · God Bless
#
#   ./Build/h7-field-clear.sh soft|resolute|once|status
#
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT="$ROOT/out"
FAST="$OUT/h7fast"
JSON="$OUT/h7_field_clear.json"
FEED="$OUT/h7_vocab_feed.tsv"
LOG="$OUT/h7_forever.log"
HEUR="$OUT/h7_secure_heuristics.tsv"
LOCK="$OUT/h7_field_clear.lock"
cmd="${1:-once}"
TS="$(date -Iseconds)"
MODE="$cmd"

n0() { local v="${1//[^0-9]/}"; echo "${v:-0}"; }

say() { echo "[$TS] FIELD_CLEAR · $*"; }

# shellcheck source=h7-desk-ports.lib.sh
. "$(cd "$(dirname "$0")" && pwd)/h7-desk-ports.lib.sh"

# measure dirt on field (fast · no sudo thrash)
# pub = thrash public only · Apache 80/443 on own IPs is desk HTTPS not dirt
measure() {
  local pub=0 scars=0 inject=0 outside=0 log_b=0 heur_n=0 feed_n=0 thrash_ps=0
  pub=$(n0 "$(count_thrash_public)")
  if [[ -f "$OUT/scar_check_latest.json" ]]; then
    scars=$(python3 -c "import json;d=json.load(open('$OUT/scar_check_latest.json'));print(d.get('scar_count',0))" 2>/dev/null || echo 0)
  fi
  if [[ -f "$OUT/av_inject_latest.json" ]]; then
    inject=$(python3 -c "import json;d=json.load(open('$OUT/av_inject_latest.json'));print(int(bool(d.get('inject_flagged',0))))" 2>/dev/null || echo 0)
  fi
  if [[ -f "$OUT/h7_secure_learn.json" ]]; then
    outside=$(python3 -c "import json;d=json.load(open('$OUT/h7_secure_learn.json'));print((d.get('inside_out') or {}).get('outside_heuristics') or 0)" 2>/dev/null || echo 0)
  fi
  [[ -f "$LOG" ]] && log_b=$(stat -c '%s' "$LOG" 2>/dev/null || echo 0)
  [[ -f "$HEUR" ]] && heur_n=$(wc -l <"$HEUR" 2>/dev/null | tr -d ' ' || echo 0)
  [[ -f "$FEED" ]] && feed_n=$(wc -l <"$FEED" 2>/dev/null | tr -d ' ' || echo 0)
  # thrash-ish process count (exact-ish · no pkill -f)
  thrash_ps=$(ps -eo comm= 2>/dev/null | awk '/^krtx-spv$|^cover$/ {c++} END{print c+0}')
  pub=$(n0 "$pub"); scars=$(n0 "$scars"); inject=$(n0 "$inject")
  outside=$(n0 "$outside"); log_b=$(n0 "$log_b"); heur_n=$(n0 "$heur_n")
  feed_n=$(n0 "$feed_n"); thrash_ps=$(n0 "$thrash_ps")
  # dirt score · higher = need resolute · desk HTTPS not dirt
  local dirt=0
  (( pub > 0 )) && dirt=$((dirt + 3))
  (( scars > 0 )) && dirt=$((dirt + scars))
  (( inject > 0 )) && dirt=$((dirt + 4))
  (( outside > 5 )) && dirt=$((dirt + 2))
  (( log_b > 8000000 )) && dirt=$((dirt + 1))
  (( heur_n > 2000 )) && dirt=$((dirt + 2))
  (( thrash_ps > 2 )) && dirt=$((dirt + 1))
  printf '%s' "$pub $scars $inject $outside $log_b $heur_n $feed_n $thrash_ps $dirt"
}

# soft · speed hygiene · love field by removing balloon thrash
soft_clear() {
  local actions=()
  # cap forever log (keep tail)
  if [[ -f "$LOG" ]]; then
    local sz
    sz=$(n0 "$(stat -c '%s' "$LOG" 2>/dev/null || echo 0)")
    if (( sz > 4000000 )); then
      tail -c 1500000 "$LOG" >"${LOG}.trim" 2>/dev/null && mv "${LOG}.trim" "$LOG" || true
      actions+=("trim_forever_log")
    fi
  fi
  # cap feed scroller · keep last 120
  if [[ -f "$FEED" ]]; then
    local fn
    fn=$(n0 "$(wc -l <"$FEED" | tr -d ' ')")
    if (( fn > 200 )); then
      tail -n 120 "$FEED" >"${FEED}.trim" 2>/dev/null && mv "${FEED}.trim" "$FEED" || true
      actions+=("trim_feed")
    fi
  fi
  # cap heuristics thrash
  if [[ -f "$HEUR" ]]; then
    local hn
    hn=$(n0 "$(wc -l <"$HEUR" | tr -d ' ')")
    if (( hn > 500 )); then
      tail -n 200 "$HEUR" >"${HEUR}.trim" 2>/dev/null && mv "${HEUR}.trim" "$HEUR" || true
      actions+=("trim_heuristics")
    fi
  fi
  # drop stale tick lock if owner dead
  if [[ -f "$OUT/h7_forever.tick.lock" ]]; then
    # flock self-test: if we can take lock briefly, previous holder is gone
    if ( flock -n 8 || exit 0; ) 8>"$OUT/h7_forever.tick.lock" 2>/dev/null; then
      : # lock free · fine
    fi
  fi
  # vocab growth log soft cap
  if [[ -f "$OUT/h7_vocab_growth.log" ]]; then
    local gsz
    gsz=$(n0 "$(stat -c '%s' "$OUT/h7_vocab_growth.log" 2>/dev/null || echo 0)")
    if (( gsz > 6000000 )); then
      tail -c 2000000 "$OUT/h7_vocab_growth.log" >"$OUT/h7_vocab_growth.log.trim" \
        && mv "$OUT/h7_vocab_growth.log.trim" "$OUT/h7_vocab_growth.log" || true
      actions+=("trim_growth_log")
    fi
  fi
  # self-intel memory soft cap
  if [[ -f "$OUT/h7_self_intel_memory.jsonl" ]]; then
    local mn
    mn=$(n0 "$(wc -l <"$OUT/h7_self_intel_memory.jsonl" | tr -d ' ')")
    if (( mn > 400 )); then
      tail -n 200 "$OUT/h7_self_intel_memory.jsonl" >"$OUT/h7_self_intel_memory.jsonl.trim" \
        && mv "$OUT/h7_self_intel_memory.jsonl.trim" "$OUT/h7_self_intel_memory.jsonl" || true
      actions+=("trim_intel_mem")
    fi
  fi
  # cook dead mega thrash · never rebuild mega_pairs.seen (old dense expand)
  if [[ -f "$OUT/h7fast/mega_pairs.seen" ]]; then
    rm -f "$OUT/h7fast/mega_pairs.seen"
    actions+=("cook_mega_pairs_seen")
  fi
  if [[ -f "$OUT/h7fast/mega.partial" ]]; then
    rm -f "$OUT/h7fast/mega.partial"
    actions+=("cook_mega_partial")
  fi
  # field love mark in feed
  printf '%s\t%s\t%s\t%s\n' "$TS" "field_love" "FIELD" "soft_clear" >>"$FEED" 2>/dev/null || true
  printf '%s' "${actions[*]:-none}"
}

# resolute · decisive clear when dirt high
resolute_clear() {
  local actions=()
  # soft first (always · speed base)
  local soft_a
  soft_a=$(soft_clear)
  [[ "$soft_a" != "none" ]] && actions+=($soft_a)

  # scar check (measure · no ceremony)
  if [[ -x "$ROOT/Build/scar-cook.sh" ]]; then
    bash "$ROOT/Build/scar-cook.sh" check >>"$OUT/h7_field_clear.log" 2>&1 || true
    actions+=("scar_check")
  fi

  # light SPV once (desk AV · not commercial stamp)
  if [[ -x "$ROOT/Build/spv-antivirus.sh" ]]; then
    timeout 25 bash "$ROOT/Build/spv-antivirus.sh" once >>"$OUT/h7_field_clear.log" 2>&1 || true
    actions+=("spv_once")
  fi

  # inject guard if present
  if [[ -x "$ROOT/Build/av-inject-guard.sh" ]]; then
    timeout 15 bash "$ROOT/Build/av-inject-guard.sh" >>"$OUT/h7_field_clear.log" 2>&1 || true
    actions+=("inject_guard")
  fi

  # secure-learn refresh (know field after clear)
  if [[ -x "$ROOT/Build/h7-secure-learn.sh" ]]; then
    timeout 40 bash "$ROOT/Build/h7-secure-learn.sh" once >>"$OUT/h7_field_clear.log" 2>&1 || true
    actions+=("secure_learn")
  fi

  # stop datacenter thrash unit if active (resolute · not continuous)
  if systemctl is-active --quiet bgrtx-datacenter.service 2>/dev/null; then
    systemctl stop bgrtx-datacenter.service 2>/dev/null || true
    actions+=("stop_datacenter_thrash")
  fi

  printf '%s\t%s\t%s\t%s\n' "$TS" "resolute_clear" "FIELD" "clear" >>"$FEED" 2>/dev/null || true
  printf '%s' "${actions[*]:-none}"
}

write_json() {
  local mode="$1" actions="$2" pub scars inject outside log_b heur_n feed_n thrash_ps dirt
  read -r pub scars inject outside log_b heur_n feed_n thrash_ps dirt <<<"$(measure)"
  # need resolute?
  local need_resolute=false
  (( dirt >= 3 )) && need_resolute=true
  local love=true
  # love stays true always · dirt is cleanup target not hate of net
  cat >"$JSON" <<EOF
{
  "ts": "$TS",
  "word": "H7_FIELD_CLEAR",
  "she": "Hostess 7",
  "philosophy": {
    "love_whole_internet": true,
    "internet_is_field": true,
    "thrash_is_dirt_not_field": true,
    "soft_clear": "speed hygiene · quality without balloon",
    "resolute_clear": "decisive cook when dirt measures high",
    "line": "love the WHOLE internet · cleanups on field · resolute clears · iron ground · never ML"
  },
  "mode": "$mode",
  "ok": true,
  "love": $love,
  "need_resolute": $need_resolute,
  "dirt_score": $dirt,
  "field": {
    "public_listen": $pub,
    "scar_count": $scars,
    "inject_flagged": $inject,
    "outside_heuristics": $outside,
    "forever_log_bytes": $log_b,
    "heuristics_lines": $heur_n,
    "feed_lines": $feed_n,
    "thrash_ps": $thrash_ps
  },
  "actions": "$(printf '%s' "$actions" | sed 's/"/\\"/g')",
  "stack": "bash+asm",
  "free_ball": true,
  "law": "love whole net as field · clear dirt · remain IN · God Bless"
}
EOF
}

run_once() {
  exec 9>"$LOCK"
  if ! flock -n 9; then
    say "skip · clear already rolling"
    return 0
  fi
  local pub scars inject outside log_b heur_n feed_n thrash_ps dirt
  read -r pub scars inject outside log_b heur_n feed_n thrash_ps dirt <<<"$(measure)"
  local actions mode_run
  if [[ "$MODE" == "soft" ]]; then
    mode_run=soft
    actions=$(soft_clear)
  elif [[ "$MODE" == "resolute" ]]; then
    mode_run=resolute
    actions=$(resolute_clear)
  else
    # once · auto: soft always · resolute if dirt high
    if (( dirt >= 3 )); then
      mode_run=resolute
      actions=$(resolute_clear)
    else
      mode_run=soft
      actions=$(soft_clear)
    fi
  fi
  write_json "$mode_run" "${actions:-none}"
  say "mode=$mode_run dirt=$dirt actions=${actions:-none} · love whole internet · field clean"
  cat "$JSON"
  flock -u 9 2>/dev/null || true
}

status() {
  if [[ -f "$JSON" ]]; then cat "$JSON"; else say "no clear yet · run soft|once|resolute"; fi
  echo "--- measure now ---"
  read -r pub scars inject outside log_b heur_n feed_n thrash_ps dirt <<<"$(measure)"
  echo "dirt=$dirt pub=$pub scars=$scars inject=$inject outside=$outside log_b=$log_b heur=$heur_n feed=$feed_n thrash_ps=$thrash_ps"
}

case "$cmd" in
  soft|resolute|once) run_once ;;
  status|measure) status ;;
  *)
    echo "usage: $0 soft|resolute|once|status" >&2
    echo "  love whole internet · cleanups on field · resolute clears" >&2
    exit 2
    ;;
esac
