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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SKILL_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
CACHE_DIR="$SKILL_DIR/cache"

usage() {
  cat <<'EOF'
Usage: read-doc.sh <doc_path> [--cursor <n>] [--limit <n>] [--version <x.y.z>]

Read a MatrixOne documentation page by its doc_path. The doc_path is obtained
from search-docs.sh output.

Environment:
  MO_DOCS_VERSION    Doc version (default: 3.0.13), overridden by --version.
EOF
  exit 0
}

DOC_PATH=""
CURSOR=0
LIMIT=8000
VERSION="${MO_DOCS_VERSION:-3.0.13}"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --cursor)  CURSOR="$2"; shift 2 ;;
    --limit)   LIMIT="$2"; shift 2 ;;
    --version) VERSION="$2"; shift 2 ;;
    -h|--help) usage ;;
    *) DOC_PATH="$1"; shift ;;
  esac
done

if [[ -z "$DOC_PATH" ]]; then
  echo "Error: doc_path is required" >&2
  usage
fi

if ! [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  echo "Error: invalid version '$VERSION'" >&2
  exit 1
fi

if [[ "$CURSOR" -lt 0 ]]; then
  echo "Error: cursor must be >= 0" >&2
  exit 1
fi

if [[ "$LIMIT" -lt 1 || "$LIMIT" -gt 20000 ]]; then
  echo "Error: limit must be between 1 and 20000" >&2
  exit 1
fi

# Build URL. doc_path may or may not have a trailing slash; strip it for the .md append.
DOC_PATH_CLEAN="${DOC_PATH%/}"
URL="https://docs.matrixorigin.cn/en/v26.${VERSION}/${DOC_PATH_CLEAN}.md"

TMPFILE=$(mktemp /tmp/mo-docs-read.XXXXXX)
trap 'rm -f "$TMPFILE"' EXIT

echo "Fetching $URL ..." >&2
if ! curl -fsSL --connect-timeout 10 --max-time 30 -o "$TMPFILE" "$URL"; then
  echo "Error: failed to fetch $URL" >&2
  exit 1
fi

TOTAL_CHARS=$(wc -m < "$TMPFILE" | tr -d ' ')

if [[ "$CURSOR" -ge "$TOTAL_CHARS" ]]; then
  echo "Error: cursor $CURSOR exceeds total chars $TOTAL_CHARS" >&2
  exit 1
fi

# Extract the requested window.
END=$((CURSOR + LIMIT))
if [[ "$END" -gt "$TOTAL_CHARS" ]]; then
  END="$TOTAL_CHARS"
fi

CONTENT=$(tail -c +$((CURSOR + 1)) "$TMPFILE" | head -c $((END - CURSOR)))
RETURNED=${#CONTENT}

NEXT_CURSOR=0
if [[ "$END" -lt "$TOTAL_CHARS" ]]; then
  NEXT_CURSOR="$END"
fi

echo "doc_path:       $DOC_PATH"
echo "source_url:     $URL"
echo "total_chars:    $TOTAL_CHARS"
echo "cursor:         $CURSOR"
echo "returned_chars: $RETURNED"
echo "next_cursor:    $NEXT_CURSOR"
echo "---"
echo "$CONTENT"
