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

# @describe Read the contents of a file at the specified path.
# Use this when you need to examine the contents of an existing file.
# @option --path! The path of the file to read
# @env LLM_OUTPUT=/dev/stdout The output path

OUT="${LLM_OUTPUT:-/dev/stdout}"
MAX_BYTES="${LLM_MAX_BYTES:-200000}"

sanitize() {
  if command -v iconv >/dev/null 2>&1; then
    iconv -f UTF-8 -t UTF-8 -c
  else
    cat
  fi
}

err() {
  echo "ERROR: $*" >> "$OUT"
  exit 0
}

main() {
  path="${argc_path:-}"
  [[ -z "$path" ]] && err "missing --path"
  [[ ! -e "$path" ]] && err "file not found: $path"
  [[ ! -f "$path" ]] && err "not a regular file: $path"
  [[ ! -r "$path" ]] && err "file not readable: $path"

  # Heuristik: Binärdateien nicht in den Chat kippen
  if LC_ALL=C grep -qP '\x00' "$path" 2>/dev/null; then
    err "file appears to be binary (NUL bytes detected): $path"
  fi

  head -c "$MAX_BYTES" "$path" | sanitize >> "$OUT"
  exit 0
}

eval "$(argc --argc-eval "$0" "$@")"
main

