#!/usr/bin/env bash
# txcontact — look up a contact by name or number.
# Usage: txcontact [-n N] [--json] [QUERY]
#   Searches termux-contact-list and prints matching contacts with
#   names, numbers and emails. With no query it lists the first N.
set -u
prog=txcontact

usage() {
  cat <<'USAGE'
Usage: txcontact [-n N] [--json] [QUERY]
  Look up contacts by name or number via termux-contact-list.
  QUERY         case-insensitive substring matched against name and number
  -n N          show at most N matches (default 10; 0 = no limit)
  --json        print the matching contacts as JSON
  --selftest    run built-in checks (fake termux-api shim + guard)
  --help        show this help
  With no QUERY, lists the first N contacts. Requires
  termux-contact-list (Termux:API); on plain Linux this prints a clear
  message and exits non-zero.
USAGE
}

render() { # render QUERY LIMIT JSONFLAG -- reads JSON array on stdin
  local q=$1 limit=$2 asjson=$3
  if command -v python3 >/dev/null 2>&1; then
    TXCONTACT_Q="$q" TXCONTACT_N="$limit" TXCONTACT_JSON="$asjson" python3 -c '
import json, os, sys
q = os.environ.get("TXCONTACT_Q", "").lower()
limit = int(os.environ.get("TXCONTACT_N", "10"))
asjson = os.environ.get("TXCONTACT_JSON", "0") == "1"
try:
    data = json.load(sys.stdin)
except Exception as e:
    print("txcontact: could not parse contact list: %s" % e, file=sys.stderr)
    sys.exit(1)
if not isinstance(data, list):
    data = [data]
def hay(c):
    parts = [str(c.get("name", "")), str(c.get("number", ""))]
    nums = c.get("numbers") or c.get("phone_numbers") or []
    if isinstance(nums, list):
        parts += [str(x) for x in nums]
    return " ".join(parts).lower()
if q:
    data = [c for c in data if q in hay(c)]
if limit > 0:
    data = data[:limit]
if asjson:
    print(json.dumps(data, indent=2))
    sys.exit(0)
if not data:
    print("no contacts matching %r" % q if q else "no contacts found")
    sys.exit(0)
for c in data:
    name = c.get("name", "?")
    nums = c.get("numbers") or c.get("phone_numbers") or []
    if isinstance(nums, str):
        nums = [nums]
    if not nums and c.get("number"):
        nums = [c["number"]]
    email = c.get("email", "")
    print("%s: %s%s" % (name, ", ".join(str(n) for n in nums) if nums else "(no number)", ("  <%s>" % email) if email else ""))
print("(%d contact%s)" % (len(data), "s" if len(data) != 1 else ""))
'
  else
    cat
    echo "note: install python3 for searching 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" "[{\"name\":\"Ada Lovelace\",\"number\":\"+1-555-0100\",\"email\":\"ada@example.com\"},{\"name\":\"Grace Hopper\",\"number\":\"+1-555-0101\"},{\"name\":\"Alan Turing\",\"number\":\"+44-20-7946-0958\"}]"' > "$tmp/bin/termux-contact-list"
  chmod +x "$tmp/bin/termux-contact-list"
  out=$(PATH="$tmp/bin:$PATH" "$self" ada 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"Ada Lovelace"* && $out == *"+1-555-0100"* && $out == *"ada@example.com"* ]]; then echo "PASS: query matches by name"; else echo "FAIL: query rc=$rc out=$out"; fails=1; fi
  out=$(PATH="$tmp/bin:$PATH" "$self" 555 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"Ada Lovelace"* && $out == *"Grace Hopper"* && $out != *"Alan Turing"* ]]; then echo "PASS: query matches by number"; else echo "FAIL: number query rc=$rc out=$out"; fails=1; fi
  out=$(PATH="$tmp/bin:$PATH" "$self" -n 1 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"(1 contact)"* ]]; then echo "PASS: -n limit respected"; else echo "FAIL: -n rc=$rc out=$out"; fails=1; fi
  out=$(PATH="$tmp/bin:$PATH" "$self" zzz 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"no contacts matching"* ]]; then echo "PASS: no-match message"; else echo "FAIL: no-match rc=$rc out=$out"; fails=1; fi
  out=$(PATH="/usr/bin:/bin" "$self" ada 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 "txcontact selftest: all PASS" || echo "txcontact selftest: $fails FAILURES"
  return $fails
}

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