#!/usr/bin/env bash
# txcall — list recent calls with durations and a missed-call filter.
# Usage: txcall [-n N] [--missed] [--from FILTER] [--json]
#   Reads termux-call-log and prints each call with a readable date,
#   direction, number/name and duration. Totals the talk time.
set -u
prog=txcall

usage() {
  cat <<'USAGE'
Usage: txcall [-n N] [--missed] [--from FILTER] [--json]
  List recent calls via termux-call-log.
  -n N          show at most N calls (default 10)
  --missed      only missed calls
  --from F      only calls involving a number/name containing F
  --json        print the matching calls as JSON
  --selftest    run built-in checks (fake termux-api shim + guard)
  --help        show this help
  Requires termux-call-log (Termux:API) and call-log permission; on
  plain Linux this prints a clear message and exits non-zero.
USAGE
}

render() { # render LIMIT MISSED FROM JSONFLAG -- reads JSON array on stdin
  local limit=$1 missed=$2 from=$3 asjson=$4
  if command -v python3 >/dev/null 2>&1; then
    TXCALL_N="$limit" TXCALL_MISSED="$missed" TXCALL_FROM="$from" TXCALL_JSON="$asjson" python3 -c '
import json, os, sys, datetime
limit = int(os.environ.get("TXCALL_N", "10"))
missed = os.environ.get("TXCALL_MISSED", "0") == "1"
frm = os.environ.get("TXCALL_FROM", "").lower()
asjson = os.environ.get("TXCALL_JSON", "0") == "1"
try:
    data = json.load(sys.stdin)
except Exception as e:
    print("txcall: could not parse call log: %s" % e, file=sys.stderr)
    sys.exit(1)
if not isinstance(data, list):
    data = [data]
def typ(c):
    t = str(c.get("type", "")).lower()
    return {"incoming": "in", "1": "in", "outgoing": "out", "2": "out", "missed": "missed", "3": "missed"}.get(t, t)
if missed:
    data = [c for c in data if typ(c) == "missed"]
if frm:
    data = [c for c in data if frm in str(c.get("number", "")).lower() or frm in str(c.get("name", "")).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 calls found")
    sys.exit(0)
total = 0
for c in data:
    num = c.get("number", "?")
    name = c.get("name", "")
    dur = c.get("duration") or 0
    try:
        dur = int(dur)
    except (TypeError, ValueError):
        dur = 0
    total += dur
    ts = c.get("date")
    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)
    who = "%s (%s)" % (name, num) if name else num
    print("[%-6s %s] %-28s %2d:%02d" % (typ(c), when, who, dur // 60, dur % 60))
print("(%d call%s, total talk time %d:%02d)" % (len(data), "s" if len(data) != 1 else "", total // 60, total % 60))
'
  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\":\"incoming\",\"number\":\"+1-555-0100\",\"name\":\"Ada Lovelace\",\"date\":1796000000000,\"duration\":125},{\"type\":\"missed\",\"number\":\"+1-555-0101\",\"name\":\"Grace Hopper\",\"date\":1796000100000,\"duration\":0},{\"type\":\"outgoing\",\"number\":\"+44-20-7946-0958\",\"name\":\"Alan Turing\",\"date\":1796000200000,\"duration\":360}]"' > "$tmp/bin/termux-call-log"
  chmod +x "$tmp/bin/termux-call-log"
  out=$(PATH="$tmp/bin:$PATH" "$self" -n 2 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"Ada Lovelace"* && $out == *"2:05"* && $out == *"(2 calls"* ]]; then echo "PASS: list with -n and durations"; else echo "FAIL: list rc=$rc out=$out"; fails=1; fi
  out=$(PATH="$tmp/bin:$PATH" "$self" --missed 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"Grace Hopper"* && $out != *"Ada Lovelace"* ]]; then echo "PASS: --missed filters"; else echo "FAIL: --missed rc=$rc out=$out"; fails=1; fi
  out=$(PATH="$tmp/bin:$PATH" "$self" --from turing 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"Alan Turing"* && $out != *"Ada Lovelace"* ]]; then echo "PASS: --from filters"; else echo "FAIL: --from rc=$rc 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 "txcall selftest: all PASS" || echo "txcall selftest: $fails FAILURES"
  return $fails
}

limit=10 missed=0 from="" asjson=0
while (( $# )); do
  case $1 in
    --help|-h) usage; exit 0;;
    --selftest) selftest; exit $?;;
    --json) asjson=1;;
    --missed) missed=1;;
    -n) shift; limit=${1:?--n 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; }
command -v termux-call-log >/dev/null 2>&1 || {
  printf '%s: termux-api not available (termux-call-log not found)\n' "$prog" >&2
  printf '%s: run this on Android with Termux:API installed and call-log permission granted.\n' "$prog" >&2
  exit 1; }
termux-call-log -l "$limit" | render "$limit" "$missed" "$from" "$asjson"
