#!/usr/bin/env bash
# txopen — open a file with its default app (or the app chooser).
# Usage: txopen [--chooser] [-c TYPE] [--dry-run] FILE
#   Wrapper around termux-open. Validates the file exists first and
#   can guess a content type from the extension when -c is not given.
set -u
prog=txopen

usage() {
  cat <<'USAGE'
Usage: txopen [--chooser] [-c TYPE] [--dry-run] FILE
  Open a file with its default Android app via termux-open.
  --chooser     show the app chooser instead of the default app
  -c TYPE       content type, e.g. application/pdf (guessed from the
                extension when omitted)
  --dry-run     print the termux-open command, do not open anything
  --selftest    run built-in checks (dry-run + validation + guard)
  --help        show this help
  Requires termux-open (Termux:API). On plain Linux the closest
  equivalent is xdg-open; this tool uses it as a fallback when
  termux-open is absent, and says so.
USAGE
}

guess_type() { # guess_type FILE -> mime-ish type or empty
  case ${1##*.} in
    pdf) printf 'application/pdf';;
    jpg|jpeg) printf 'image/jpeg';;
    png) printf 'image/png';;
    gif) printf 'image/gif';;
    webp) printf 'image/webp';;
    mp3) printf 'audio/mpeg';;
    mp4) printf 'video/mp4';;
    txt|md) printf 'text/plain';;
    html|htm) printf 'text/html';;
    zip) printf 'application/zip';;
    apk) printf 'application/vnd.android.package-archive';;
    *) if command -v file >/dev/null 2>&1; then file -b --mime-type "$1" 2>/dev/null; fi;;
  esac
}

selftest() {
  local tmp fails=0 out rc
  tmp=$(mktemp -d); trap "rm -rf '$tmp'" EXIT
  local self="${BASH_SOURCE[0]}"
  printf 'fake pdf' > "$tmp/doc.pdf"
  out=$("$self" --dry-run --chooser "$tmp/doc.pdf" 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"termux-open"* && $out == *"--chooser"* && $out == *"$tmp/doc.pdf"* && $out == *"application/pdf"* ]]; then echo "PASS: --dry-run with chooser + guessed type"; else echo "FAIL: dry-run rc=$rc out=$out"; fails=1; fi
  out=$("$self" --dry-run -c text/plain "$tmp/doc.pdf" 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"text/plain"* ]]; then echo "PASS: explicit -c type wins"; else echo "FAIL: -c rc=$rc out=$out"; fails=1; fi
  out=$("$self" --dry-run "$tmp/missing.pdf" 2>&1); rc=$?
  if (( rc != 0 )) && [[ $out == *"no such file"* ]]; then echo "PASS: missing file rejected"; else echo "FAIL: missing rc=$rc out=$out"; fails=1; fi
  out=$("$self" --dry-run 2>&1); rc=$?
  if (( rc != 0 )); then echo "PASS: no file rejected"; else echo "FAIL: no-file should fail"; fails=1; fi
  out=$(PATH="/usr/bin:/bin" "$self" "$tmp/doc.pdf" 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 "txopen selftest: all PASS" || echo "txopen selftest: $fails FAILURES"
  return $fails
}

chooser=0 ctype="" dryrun=0 file=""
while (( $# )); do
  case $1 in
    --help|-h) usage; exit 0;;
    --selftest) selftest; exit $?;;
    --dry-run) dryrun=1;;
    --chooser) chooser=1;;
    -c) shift; ctype=${1:?-c needs a value};;
    -*) echo "$prog: unknown option: $1" >&2; usage >&2; exit 1;;
    *) [[ -z $file ]] && file=$1 || { echo "$prog: only one file at a time" >&2; exit 1; };;
  esac
  shift
done
[[ -n $file ]] || { echo "$prog: need a file to open" >&2; usage >&2; exit 1; }
[[ -f $file ]] || { echo "$prog: no such file: $file" >&2; exit 1; }
[[ -n $ctype ]] || ctype=$(guess_type "$file")
args=()
(( chooser )) && args+=(--chooser)
[[ -n $ctype ]] && args+=(-c "$ctype")
args+=("$file")
if (( dryrun )); then printf 'termux-open'; printf ' %q' "${args[@]}"; printf '\n'; exit 0; fi
if command -v termux-open >/dev/null 2>&1; then
  termux-open "${args[@]}"
elif command -v xdg-open >/dev/null 2>&1; then
  echo "$prog: termux-open not found; Linux fallback: opening with xdg-open" >&2
  xdg-open "$file"
else
  printf '%s: termux-api not available (termux-open not found) and no xdg-open fallback.\n' "$prog" >&2
  printf '%s: run this on Android with Termux:API installed, or on a Linux desktop with xdg-open.\n' "$prog" >&2
  exit 1
fi
