#!/usr/bin/env bash
# description: Read a file from the local filesystem with optional offset and line limit
# Args: <file_path> [offset] [limit]

file_path="$1"
offset="${2:-1}"
limit="${3:-2000}"
max_line_len=2000
max_size=$((8 * 1024 * 1024))

[ -z "$file_path" ] && echo "usage: file_read <file_path> [offset] [limit]" && exit 1
[[ "$file_path" != /* ]] && echo "error: path must be absolute, got: $file_path" && exit 1
[ ! -e "$file_path" ] && echo "error: file not found: $file_path" && exit 1
[ ! -f "$file_path" ] && echo "error: not a regular file: $file_path" && exit 1

size=$(wc -c < "$file_path")
[ "$size" -gt "$max_size" ] && echo "error: file too large ($size bytes, max $max_size)" && exit 1

content=$(awk -v off="$offset" -v lim="$limit" -v maxlen="$max_line_len" '
    NR >= off && NR < off+lim {
        if (length($0) > maxlen) print substr($0, 1, maxlen) "..."
        else print
    }
    NR >= off+lim { exit }
' "$file_path")

if [ -z "$content" ]; then
    echo "(empty file)"
else
    printf '%s\n' "$content"
fi

# save content to marker (used by file_edit/file_write as staging area)
mkdir -p "/tmp/ollie/$OLLIE_SESSION_ID"
marker="/tmp/ollie/$OLLIE_SESSION_ID/$(printf '%s' "$file_path" | sha256sum | cut -c1-64)"
cp "$file_path" "$marker"
