#!/usr/bin/env bash
# txsms — list recent SMS messages with a count.
# Usage: txsms [-n N] [-t TYPE] [--from FILTER] [--full] [--json]
#   Reads termux-sms-list and prints each message with a readable date,
#   direction, number and a truncated body. Filters by sender and type.
set -u
prog=txsms

usage() {
  cat <<'USAGE'
Usage: txsms [-n N] [-t TYPE] [--from FILTER] [--full] [--json]
  List recent SMS messages via termux-sms-list.
  -n N          show at most N messages (default 10)
  -t TYPE       inbox|sent|draft|outbox|failed|queued (default: inbox)
  --from F      only messages from a number/name containing F
  --full        show the whole body instead of truncating at 120 chars
  --json        print the matching messages as JSON
  --selftest    run built-in checks (fake termux-api shim + guard)
  --help        show this help
  Requires termux-sms-list (Termux:API) and SMS permission; on plain
  Linux this prints a clear message and exits non-zero.
USAGE
}

render() { # render LIMIT TYPE FROM FULL JSONFLAG -- reads JSON array on stdin
  local limit=$1 type=$2 from=$3 full=$4 asjson=$5
  if command -v python3 >/dev/null 2>&1; then
    TXSMS_N="$limit" TXSMS_T="$type" TXSMS_FROM="$from" TXSMS_FULL="$full" TXSMS_JSON="$asjson" python3 -c '
import json, os, sys, datetime
limit = int(os.environ.get("TXSMS_N", "10"))
want_type = os.environ.get("TXSMS_T", "")
frm = os.environ.get("TXSMS_FROM", "").lower()
full = os.environ.get("TXSMS_FULL", "0") == "1"
asjson = os.environ.get("TXSMS_JSON", "0") == "1"
try:
    data = json.load(sys.stdin)
except Exception as e:
    print("txsms: could not parse SMS list: %s" % e, file=sys.stderr)
    sys.exit(1)
if not isinstance(data, list):
    data = [data]
def typ(m):
    t = str(m.get("type", "")).lower()
    return {"inbox": "in", "received": "in", "1": "in", "sent": "out", "2": "out"}.get(t, t)
if want_type:
    data = [m for m in data if typ(m) == want_type or str(m.get("type", "")).lower() == want_type]
if frm:
    data = [m for m in data if frm in str(m.get("number", "")).lower() or frm in str(m.get("sender", "")).lower()]
data = data[:limit] if limit > 0 else data
if asjson:
    print(json.dumps(data, indent=2))
    sys.exit(0)
if not data:
    print("no SMS messages found")
    sys.exit(0)
for m in data:
    num = m.get("number") or m.get("sender") or "?"
    body = str(m.get("body", ""))
    ts = m.get("received") or m.get("date") or m.get("sent")
    when = "?"
    if isinstance(ts, (int, float)):
        sec = ts / 1000.0 if ts > 10**12 else ts
        when = datetime.datetime.fromtimestamp(sec).strftime("%Y-%m-%d %H:%M")
    elif ts:
        when = str(ts)
    if not full and len(body) > 120:
        body = body[:117] + "..."
    print("[%s %s] %s: %s" % (typ(m), when, num, body))
print("(%d message%s)" % (len(data), "s" if len(data) != 1 else ""))
'
  else
    cat
    echo "note: install python3 for filtering and formatting" >&2
  fi
}

selftest() {
  local tmp fails=0 out rc
  tmp=$(mktemp -d); trap "rm -rf '$tmp'" EXIT
  local self="${BASH_SOURCE[0]}"
  mkdir -p "$tmp/bin"
  printf '%s\n' '#!/usr/bin/env bash' 'printf "%s" "[{\"type\":\"inbox\",\"number\":\"+1-555-0100\",\"body\":\"Hello there, this is a test message from Ada.\",\"received\":1796000000000},{\"type\":\"sent\",\"number\":\"+1-555-0101\",\"body\":\"Reply from me.\",\"received\":1796000100000},{\"type\":\"inbox\",\"number\":\"+44-20-7946-0958\",\"body\":\"Tea?\",\"received\":1796000200000}]"' > "$tmp/bin/termux-sms-list"
  chmod +x "$tmp/bin/termux-sms-list"
  out=$(PATH="$tmp/bin:$PATH" "$self" -n 2 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"+1-555-0100"* && $out == *"Hello there"* && $out == *"(2 messages)"* ]]; then echo "PASS: list with -n limit"; else echo "FAIL: list rc=$rc out=$out"; fails=1; fi
  out=$(PATH="$tmp/bin:$PATH" "$self" -t sent 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"Reply from me"* && $out != *"Hello there"* ]]; then echo "PASS: -t sent filters"; else echo "FAIL: -t rc=$rc out=$out"; fails=1; fi
  out=$(PATH="$tmp/bin:$PATH" "$self" --from 555-0100 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"Hello there"* && $out != *"Tea?"* ]]; then echo "PASS: --from filters"; else echo "FAIL: --from rc=$rc out=$out"; fails=1; fi
  out=$(PATH="$tmp/bin:$PATH" "$self" -t inbox --json 2>&1)
  if [[ $out == *'"type": "inbox"'* || $out == *'"type":"inbox"'* ]]; then echo "PASS: --json output"; else echo "FAIL: --json out=$out"; fails=1; fi
  out=$(PATH="/usr/bin:/bin" "$self" 2>&1); rc=$?
  if (( rc != 0 )) && [[ $out == *"termux-api not available"* ]]; then echo "PASS: graceful degradation message"; else echo "FAIL: guard rc=$rc 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 "txsms selftest: all PASS" || echo "txsms selftest: $fails FAILURES"
  return $fails
}

limit=10 type=inbox from="" full=0 asjson=0
while (( $# )); do
  case $1 in
    --help|-h) usage; exit 0;;
    --selftest) selftest; exit $?;;
    --json) asjson=1;;
    --full) full=1;;
    -n) shift; limit=${1:?--n needs a value};;
    -t) shift; type=${1:?--t needs a value};;
    --from) shift; from=${1:?--from needs a value};;
    *) echo "$prog: unknown option: $1" >&2; usage >&2; exit 1;;
  esac
  shift
done
[[ $limit =~ ^[0-9]+$ ]] || { echo "$prog: -n must be a number, got '$limit'" >&2; exit 1; }
case $type in inbox|sent|draft|outbox|failed|queued) ;; *) echo "$prog: -t must be inbox|sent|draft|outbox|failed|queued, got '$type'" >&2; exit 1;; esac
command -v termux-sms-list >/dev/null 2>&1 || {
  printf '%s: termux-api not available (termux-sms-list not found)\n' "$prog" >&2
  printf '%s: run this on Android with Termux:API installed and SMS permission granted.\n' "$prog" >&2
  exit 1; }
termux-sms-list -l "$limit" -t "$type" | render "$limit" "$type" "$from" "$full" "$asjson"
