#!/usr/bin/env bash
set -euo pipefail

log_error() {
  echo "❌ $1" >&2
  exit 1
}

show_usage() {
  echo "Usage:"
  echo "  kautolog -r <log_base>        # Replays with timing"
  echo "  kautolog -i <log_base>        # Instantly dumps log without timing"
  echo "Options:"
  echo "  -d <speed>        Scriptreplay speed delay"
  echo "  -m <maxdelay>     Max delay between lines"
  echo "  --target <secs>   Target duration in seconds"
  exit 1
}

# --- args ---
replay=0
instant=0
speed_args=()
maxdelay=""
target=""
logbase=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    -r|--replay)
      replay=1
      shift
      ;;
    -i|--instant)
      instant=1
      shift
      ;;
    -d)
      speed_args+=("-d" "$2")
      shift 2
      ;;
    -m|--maxdelay)
      maxdelay="$2"
      shift 2
      ;;
    --target)
      target="$2"
      shift 2
      ;;
    -*)
      log_error "Unknown option: $1"
      ;;
    *)
      logbase="$1"
      shift
      ;;
  esac
done

[[ -z "$logbase" ]] && show_usage
[[ "$replay" -eq 0 && "$instant" -eq 0 ]] && show_usage

base="${logbase%.log}"
log="$(realpath -m "${base}.log")"
timing="$(realpath -m "${base}.timing")"
live_log="$(realpath -m "${logbase:-nonexistent}.log" 2>/dev/null || true)"

[[ -n "${logbase:-}" && "$log" == "$live_log" ]] && log_error "❌ Refusing to replay the current live session log due to recursion."

saved=$(stty -g 2>/dev/null || true)
_restore() {
  stty "$saved" 2>/dev/null || true
  printf '\e[?7h\e[?25h'
  echo
  trap - INT EXIT
}
trap _restore INT EXIT

if [[ "$instant" -eq 1 ]]; then
  [[ -f "$log" ]] || log_error "Missing: $log"
  echo "Instant dump of: $log"
  cat -- "$log"
else
  [[ -f "$log" && -f "$timing" ]] || log_error "Missing: $log or $timing"
  total=$(awk '{s+=$1} END{print int(s+0.5)}' "$timing" || echo 1)
  (( total<=0 )) && total=1
  if [[ -n "$target" && "$target" -gt 0 ]]; then
    d=$(( total / target ))
    (( d<1 )) && d=1
    speed_args=( "-d" "$d" )
    [[ -z "$maxdelay" ]] && maxdelay="0.12"
  fi

  echo "Replaying: $log"
  echo "Tips: Ctrl+C to stop early; you’ll stay on this screen."

  cmd=( /usr/bin/scriptreplay )
  [[ ${#speed_args[@]} -gt 0 ]] && cmd+=( "${speed_args[@]}" )
  [[ -n "$maxdelay" ]] && cmd+=( --maxdelay "$maxdelay" )
  cmd+=( -t "$timing" "$log" )

  "${cmd[@]}"
fi

_restore
echo "✅ Back to your shell."
