#!/usr/bin/env bash
# txtermux — Termux environment report: version, storage, API
# availability, health check.
# Usage: txtermux [--json] [--quiet]
#   Prints one health report: whether this is Termux at all, the
#   Android version, which termux-api commands are present, storage
#   setup, and the tool versions the other tx* tools rely on.
#   Exits 0 even when things are missing — it is a report, and the
#   missing pieces are the findings.
set -u
prog=txtermux

usage() {
  cat <<'USAGE'
Usage: txtermux [--json] [--quiet]
  Termux environment health report.
  --json        print the report as JSON
  --quiet       print only the one-line verdict
  --selftest    run built-in checks (report sections + fake API shim)
  --help        show this help
  Checks: Termux install, Android version, every termux-api command
  the tx* tools use, storage access, and bash/python3 versions.
  Always exits 0: missing pieces are findings, not failures.
USAGE
}

API_CMDS="termux-battery-status termux-clipboard-get termux-clipboard-set termux-notification termux-vibrate termux-torch termux-wifi-connectioninfo termux-wallpaper termux-contact-list termux-sms-list termux-call-log termux-location termux-share termux-open termux-sensor termux-media-scan termux-brightness termux-volume termux-tts-speak termux-dialog termux-wake-lock termux-wake-unlock termux-usb termux-telephony-deviceinfo termux-download termux-storage-info"

check_api() { # check_api -> "have missing" counts, prints matrix to stdout
  local have=0 missing=0 c
  for c in $API_CMDS; do
    if command -v "$c" >/dev/null 2>&1; then have=$((have+1)); printf '  [ok]      %s\n' "$c";
    else missing=$((missing+1)); printf '  [missing] %s\n' "$c"; fi
  done
  printf 'API_COVERAGE %s %s\n' "$have" "$missing"
}

report_text() {
  local have missing total problems=0
  echo "Termux environment report"
  echo "========================="
  if [[ -n ${PREFIX:-} && -d ${PREFIX:-/nonexistent} ]]; then
    echo "Termux: yes ($PREFIX)"
    [[ -n ${TERMUX_VERSION:-} ]] && echo "Termux version: $TERMUX_VERSION"
  else
    echo "Termux: no (PREFIX not set — plain Linux, not Termux)"
    problems=$((problems+1))
  fi
  if command -v getprop >/dev/null 2>&1; then
    echo "Android: $(getprop ro.build.version.release 2>/dev/null || echo ?) (SDK $(getprop ro.build.version.sdk 2>/dev/null || echo ?), $(getprop ro.product.model 2>/dev/null || echo ?))"
  else
    echo "Android: n/a (getprop not found)"
  fi
  echo "termux-api commands:"
  local matrix
  matrix=$(check_api)
  printf '%s\n' "$matrix" | grep -v '^API_COVERAGE'
  have=$(printf '%s\n' "$matrix" | awk '/^API_COVERAGE/ {print $2}')
  missing=$(printf '%s\n' "$matrix" | awk '/^API_COVERAGE/ {print $3}')
  total=$(( have + missing ))
  echo "API coverage: $have/$total commands present"
  (( missing > 0 )) && problems=$((problems+1))
  if [[ -n ${PREFIX:-} ]]; then
    if [[ -d $HOME/storage ]]; then echo "Storage access: set up ($HOME/storage)"; else echo "Storage access: NOT set up — run termux-setup-storage"; problems=$((problems+1)); fi
  else
    echo "Storage access: n/a (not Termux)"
  fi
  echo "Disk ($HOME): $(df -h "$HOME" 2>/dev/null | awk 'NR==2 {print $4 " free of " $2 " (" $5 " used)"}')"
  echo "bash: ${BASH_VERSION%% *}   python3: $(python3 --version 2>&1 | awk '{print $2}')"
  if [[ -n ${PREFIX:-} ]] && (( missing == 0 )); then
    echo "Verdict: HEALTHY — Termux + Termux:API fully available"
  elif [[ -n ${PREFIX:-} ]]; then
    echo "Verdict: DEGRADED — Termux present but $missing termux-api command(s) missing (install Termux:API and grant permissions)"
  else
    echo "Verdict: NOT TERMUX — plain Linux; tx* tools will use fallbacks or report termux-api as unavailable"
  fi
  return 0
}

report_json() {
  if command -v python3 >/dev/null 2>&1; then
    TXTERMUX_CMDS="$API_CMDS" python3 -c '
import json, os, shutil, subprocess, sys
cmds = os.environ.get("TXTERMUX_CMDS", "").split()
prefix = os.environ.get("PREFIX", "")
home = os.environ.get("HOME", "")
api = {c: shutil.which(c) is not None for c in cmds}
have = sum(api.values())
android = None
try:
    rel = subprocess.run(["getprop", "ro.build.version.release"], capture_output=True, text=True, timeout=5)
    android = rel.stdout.strip() or None
except Exception:
    android = None
try:
    df = subprocess.run(["df", "-B1", "--output=avail,size", home or "/"], capture_output=True, text=True, timeout=5).stdout.splitlines()
    avail, size = (int(x) for x in df[1].split()) if len(df) > 1 else (None, None)
except Exception:
    avail, size = None, None
report = {
    "termux": bool(prefix),
    "prefix": prefix or None,
    "termux_version": os.environ.get("TERMUX_VERSION"),
    "android": android,
    "storage_access": os.path.isdir(os.path.join(home, "storage")) if home else False,
    "api": api,
    "api_coverage": "%d/%d" % (have, len(cmds)),
    "disk_free_bytes": avail,
    "disk_size_bytes": size,
    "bash": os.environ.get("BASH_VERSION", ""),
    "python3": shutil.which("python3") is not None,
}
print(json.dumps(report, indent=2))
'
  else
    echo "$prog: python3 is needed for --json; showing text report instead" >&2
    report_text
  fi
}

selftest() {
  local tmp fails=0 out rc
  tmp=$(mktemp -d); trap "rm -rf '$tmp'" EXIT
  local self="${BASH_SOURCE[0]}"
  out=$("$self" 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"Termux environment report"* && $out == *"API coverage:"* && $out == *"Verdict:"* ]]; then echo "PASS: report has all sections"; else echo "FAIL: report rc=$rc out=$out"; fails=1; fi
  if [[ $out == *"NOT TERMUX"* ]]; then echo "PASS: plain-Linux verdict on this box"; else echo "FAIL: verdict should say NOT TERMUX, got: $out"; fails=1; fi
  if [[ $out == *"[missing] termux-battery-status"* ]]; then echo "PASS: API matrix lists missing commands"; else echo "FAIL: matrix missing battery entry"; fails=1; fi
  out=$("$self" --json 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *'"api_coverage"'* && $out == *'"termux": false'* ]]; then echo "PASS: --json report"; else echo "FAIL: --json rc=$rc out=$out"; fails=1; fi
  out=$("$self" --quiet 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"Verdict:"* ]]; then echo "PASS: --quiet prints the verdict"; else echo "FAIL: --quiet rc=$rc out=$out"; fails=1; fi
  mkdir -p "$tmp/bin"
  printf '%s\n' '#!/usr/bin/env bash' 'exit 0' > "$tmp/bin/termux-battery-status"
  printf '%s\n' '#!/usr/bin/env bash' 'exit 0' > "$tmp/bin/termux-vibrate"
  chmod +x "$tmp/bin/termux-battery-status" "$tmp/bin/termux-vibrate"
  out=$(PATH="$tmp/bin:$PATH" "$self" 2>&1)
  if [[ $out == *"[ok]      termux-battery-status"* && $out == *"API coverage: 2/"* ]]; then echo "PASS: API matrix detects present commands"; else echo "FAIL: shim matrix out=$out"; fails=1; fi
  out=$("$self" --help 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"Usage:"* ]]; then echo "PASS: --help"; else echo "FAIL: --help rc=$rc"; fails=1; fi
  (( fails == 0 )) && echo "txtermux selftest: all PASS" || echo "txtermux selftest: $fails FAILURES"
  return $fails
}

mode=text
while (( $# )); do
  case $1 in
    --help|-h) usage; exit 0;;
    --selftest) selftest; exit $?;;
    --json) mode=json;;
    --quiet) mode=quiet;;
    *) echo "$prog: unknown option: $1" >&2; usage >&2; exit 1;;
  esac
  shift
done
case $mode in
  text) report_text;;
  json) report_json;;
  quiet) report_text | grep '^Verdict:';;
esac
exit 0
