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

# @describe Write the full file contents to a file at the specified path.
# @option --path! The path of the file to write to
# @option --contents! The full contents to write to the file
# @env LLM_OUTPUT=/dev/stdout The output path

ROOT_DIR="${LLM_ROOT_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
OUT="${LLM_OUTPUT:-/dev/stdout}"

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

main() {
  path="${argc_path:-}"
  contents="${argc_contents:-}"

  [[ -z "$path" ]] && err "missing --path"
  # contents darf leer sein – das ist erlaubt (File leeren)
  dir="$(dirname "$path")"

  if [[ -e "$path" && ! -f "$path" ]]; then
    err "target exists but is not a regular file: $path"
  fi

  if [[ -f "$path" ]]; then
    # Diff in Output schreiben (damit LLM es sieht)
    printf "%s" "$contents" | git diff --no-index "$path" - >> "$OUT" 2>/dev/null || true
    if ! "$ROOT_DIR/utils/guard_operation.sh" "Apply changes?" >>"$OUT" 2>&1; then
      err "operation cancelled by user"
    fi
  else
    if ! "$ROOT_DIR/utils/guard_path.sh" "$path" "Write '$path'?" >>"$OUT" 2>&1; then
      err "operation cancelled by user"
    fi
    if ! mkdir -p "$dir" 2>/tmp/fs_write_mkdir.err; then
      msg="$(cat /tmp/fs_write_mkdir.err 2>/dev/null || true)"
      err "failed to create parent dir $dir: ${msg:-unknown error}"
    fi
  fi

  if ! printf "%s" "$contents" > "$path" 2>/tmp/fs_write.err; then
    msg="$(cat /tmp/fs_write.err 2>/dev/null || true)"
    err "failed to write file $path: ${msg:-unknown error}"
  fi

  echo "The contents written to: $path" >> "$OUT"
  exit 0
}

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

