#!/usr/bin/env bash
# txbattery — battery status with a human summary and charge estimate.
# Usage: txbattery [--json] [--watch SECONDS]
#   On Android uses termux-battery-status; on plain Linux reads
#   /sys/class/power_supply. When /sys charge counters are present
#   (also readable on Android) it estimates time to full / empty.
set -u
prog=txbattery
SYSFS="${TXBATTERY_SYSFS:-/sys/class/power_supply}"

usage() {
  cat <<'USAGE'
Usage: txbattery [--json] [--watch SECONDS]
  Show battery status as a human summary.
  --json        print the raw termux-battery-status JSON (or a sysfs-built
                equivalent on plain Linux) instead of the summary
  --watch N     reprint the summary every N seconds until interrupted
  --selftest    run built-in checks (fake sysfs + fake termux-api shim)
  --help        show this help
  On Android this uses termux-battery-status; on plain Linux it reads
  /sys/class/power_supply. If neither is available it says so plainly.
USAGE
}

bar() { # bar PCT [WIDTH]
  local pct=${1:-0} w=${2:-20} filled i s=""
  (( pct < 0 )) && pct=0; (( pct > 100 )) && pct=100
  filled=$(( pct * w / 100 ))
  for ((i=0; i<w; i++)); do if (( i < filled )); then s+="█"; else s+="░"; fi; done
  printf '%s' "$s"
}

fmt_mins() { # fmt_mins MINUTES -> "4h 00m" | "45m" | "unknown"
  local m=${1:--1}
  if (( m < 0 )); then printf 'unknown'; return 0; fi
  if (( m >= 60 )); then printf '%dh %02dm' $((m/60)) $((m%60)); else printf '%dm' "$m"; fi
}

sysfs_file() { # sysfs_file DIR KEY -> trimmed contents or empty
  local f="$1/$2"
  [[ -r $f ]] || return 0
  tr -d ' \t\r\n' < "$f"
}

find_batt_dir() {
  local d
  for d in "$SYSFS"/BAT* "$SYSFS"/battery; do
    [[ -d $d ]] && { printf '%s' "$d"; return 0; }
  done
  return 1
}

# sysfs_estimate DIR STATUS -> "to full: 1h 20m" | "to empty: 3h 05m" | ""
sysfs_estimate() {
  local dir=$1 status=$2 now full cur remain mins
  now=$(sysfs_file "$dir" charge_now); [[ -z $now ]] && now=$(sysfs_file "$dir" energy_now)
  full=$(sysfs_file "$dir" charge_full); [[ -z $full ]] && full=$(sysfs_file "$dir" energy_full)
  cur=$(sysfs_file "$dir" current_now); [[ -z $cur ]] && cur=$(sysfs_file "$dir" power_now)
  [[ -n $now && -n $full && -n $cur ]] || return 0
  [[ $cur =~ ^[0-9]+$ ]] || return 0
  (( cur <= 0 )) && return 0
  if [[ $status == *Charg* ]]; then remain=$(( full - now )); (( remain <= 0 )) && { printf 'full now'; return 0; }
    mins=$(( remain * 60 / cur )); printf 'to full: %s' "$(fmt_mins "$mins")"
  else remain=$now; mins=$(( remain * 60 / cur )); printf 'to empty: %s' "$(fmt_mins "$mins")"; fi
}

sysfs_summary() {
  local dir pct status health temp volt est line
  dir=$(find_batt_dir) || return 1
  pct=$(sysfs_file "$dir" capacity)
  status=$(sysfs_file "$dir" status); [[ -z $status ]] && status=Unknown
  health=$(sysfs_file "$dir" health); [[ -z $health ]] && health=Unknown
  temp=$(sysfs_file "$dir" temp)
  volt=$(sysfs_file "$dir" voltage_now)
  [[ -n $pct ]] || return 1
  line="Battery: ${pct}% [$(bar "$pct")] ${status} (health: ${health})"
  [[ -n $temp ]] && line+=" temp: $(( temp / 10 )).$(( (temp % 10 + 5) / 10 ))°C"
  [[ -n $volt ]] && line+=" voltage: $(( volt / 1000000 )).$(( (volt / 10000) % 100 ))V"
  est=$(sysfs_estimate "$dir" "$status"); [[ -n $est ]] && line+=" — ${est}"
  printf '%s\n' "$line"
}

sysfs_json() {
  local dir pct status health temp volt cur now full
  dir=$(find_batt_dir) || return 1
  pct=$(sysfs_file "$dir" capacity); status=$(sysfs_file "$dir" status)
  health=$(sysfs_file "$dir" health); temp=$(sysfs_file "$dir" temp)
  volt=$(sysfs_file "$dir" voltage_now); cur=$(sysfs_file "$dir" current_now)
  now=$(sysfs_file "$dir" charge_now); full=$(sysfs_file "$dir" charge_full)
  printf '{"source":"sysfs","percentage":%s,"status":"%s","health":"%s","temperature":%s,"voltage":%s,"current":%s,"charge_now":%s,"charge_full":%s}\n' \
    "${pct:-null}" "${status:-Unknown}" "${health:-Unknown}" \
    "${temp:+$((temp/10))}" "${volt:-null}" "${cur:-null}" "${now:-null}" "${full:-null}"
}

render_termux_json() {
  if command -v python3 >/dev/null 2>&1; then
    python3 -c '
import json, sys
d = json.load(sys.stdin)
pct = d.get("percentage")
status = d.get("status", "unknown")
health = d.get("health", "unknown")
plugged = d.get("plugged", "unknown")
temp = d.get("temperature")
cur = d.get("current")
w = 20
filled = 0 if pct is None else max(0, min(w, pct * w // 100))
bar = "█" * filled + "░" * (w - filled)
line = "Battery: %s%% [%s] %s (health: %s, plugged: %s)" % (pct, bar, status, health, plugged)
if temp is not None:
    line += " temp: %s°C" % temp
if cur is not None:
    line += " current: %s mA" % cur
print(line)
'
  else
    cat
    echo "note: install python3 for a human-readable summary" >&2
  fi
}

show_once() {
  local json=${1:-0}
  if command -v termux-battery-status >/dev/null 2>&1; then
    if (( json )); then termux-battery-status; return 0; fi
    termux-battery-status | render_termux_json
    local dir est
    if dir=$(find_batt_dir 2>/dev/null); then
      est=$(sysfs_estimate "$dir" "$(sysfs_file "$dir" status)")
      [[ -n $est ]] && printf 'Charge estimate (from /sys counters): %s\n' "$est"
    fi
    return 0
  fi
  if (( json )); then sysfs_json || {
    printf '%s: termux-api not available (termux-battery-status not found) and no battery in %s\n' "$prog" "$SYSFS" >&2
    printf '%s: run this on Android with Termux:API installed, or on a Linux machine with a battery.\n' "$prog" >&2
    return 1; }
    return 0
  fi
  sysfs_summary || {
    printf '%s: termux-api not available (termux-battery-status not found) and no battery in %s\n' "$prog" "$SYSFS" >&2
    printf '%s: run this on Android with Termux:API installed, or on a Linux machine with a battery.\n' "$prog" >&2
    return 1; }
}

selftest() {
  local tmp fails=0 out rc
  tmp=$(mktemp -d); trap "rm -rf '$tmp'" EXIT
  local self="${BASH_SOURCE[0]}"
  # 1. fake sysfs: 50%, discharging, 2,000,000/4,000,000 uAh at 500,000 uA -> ~4h to empty
  mkdir -p "$tmp/ps/BAT0" "$tmp/empty"
  printf '50' > "$tmp/ps/BAT0/capacity"; printf 'Discharging' > "$tmp/ps/BAT0/status"
  printf 'Good' > "$tmp/ps/BAT0/health"; printf '2000000' > "$tmp/ps/BAT0/charge_now"
  printf '4000000' > "$tmp/ps/BAT0/charge_full"; printf '500000' > "$tmp/ps/BAT0/current_now"
  printf '3800000' > "$tmp/ps/BAT0/voltage_now"
  out=$(TXBATTERY_SYSFS="$tmp/ps" "$self" 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"50%"* && $out == *"4h 00m"* ]]; then echo "PASS: sysfs fallback summary + estimate"; else echo "FAIL: sysfs summary rc=$rc out=$out"; fails=1; fi
  # 2. fake termux shim
  mkdir -p "$tmp/bin"
  printf '%s\n' '#!/usr/bin/env bash' 'printf "%s" "{\"health\":\"GOOD\",\"percentage\":87,\"plugged\":\"PLUGGED_AC\",\"status\":\"CHARGING\",\"temperature\":28.5,\"current\":512}"' > "$tmp/bin/termux-battery-status"
  chmod +x "$tmp/bin/termux-battery-status"
  out=$(TXBATTERY_SYSFS="$tmp/empty" PATH="$tmp/bin:$PATH" "$self" 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"87%"* && $out == *"CHARGING"* ]]; then echo "PASS: termux-battery-status path"; else echo "FAIL: termux path rc=$rc out=$out"; fails=1; fi
  # 3. --json through the shim
  out=$(TXBATTERY_SYSFS="$tmp/empty" PATH="$tmp/bin:$PATH" "$self" --json 2>&1)
  if [[ $out == *'"percentage":87'* ]]; then echo "PASS: --json passthrough"; else echo "FAIL: --json out=$out"; fails=1; fi
  # 4. graceful degradation: no termux-api, no battery
  out=$(TXBATTERY_SYSFS="$tmp/empty" 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
  # 5. --help
  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 "txbattery selftest: all PASS" || echo "txbattery selftest: $fails FAILURES"
  return $fails
}

json=0 watch=0
while (( $# )); do
  case $1 in
    --help|-h) usage; exit 0;;
    --selftest) selftest; exit $?;;
    --json) json=1;;
    --watch) shift; watch=${1:?--watch needs seconds}; [[ $watch =~ ^[0-9]+$ ]] || { echo "$prog: --watch needs a number" >&2; exit 1; };;
    *) echo "$prog: unknown option: $1" >&2; usage >&2; exit 1;;
  esac
  shift
done
if (( watch > 0 )); then
  while true; do show_once "$json"; sleep "$watch"; done
else
  show_once "$json"
fi
