#!/bin/bash
set -euo pipefail

LOG_FILE="${1:-}"

if [ -z "$LOG_FILE" ]; then
  for candidate in "./didactyl.log" "./debug.log" "./context.log.md"; do
    if [ -f "$candidate" ]; then
      LOG_FILE="$candidate"
      break
    fi
  done
fi

if [ -z "$LOG_FILE" ] || [ ! -f "$LOG_FILE" ]; then
  echo "Log file not found." >&2
  echo "Tried defaults: ./didactyl.log ./debug.log ./context.log.md" >&2
  echo "Usage: $0 [path/to/logfile]" >&2
  exit 1
fi

echo "Following numbered LLM API calls from: $LOG_FILE"
echo "(Press Ctrl+C to stop)"

# Count only outbound provider calls from src/llm.c:
#   [didactyl] llm request: method=... url=...
START_API=$(tail -n 20000 "$LOG_FILE" | grep -Ec "\\[didactyl\\] llm request:" || true)
[ -z "$START_API" ] && START_API=0

echo "Starting api_call count from: $START_API"

tail -n 0 -F "$LOG_FILE" \
  | awk -v api_start="$START_API" '
      BEGIN { api = api_start }
      {
        line = $0
        if (line !~ /\[didactyl\] llm request:/) next

        api++
        method = "?"
        url = "?"

        if (match(line, /method=[A-Z]+/)) {
          method = substr(line, RSTART + 7, RLENGTH - 7)
        }
        if (match(line, /url=[^ ]+/)) {
          url = substr(line, RSTART + 4, RLENGTH - 4)
        }

        printf "%d) %s %s\n", api, method, url
        fflush()
      }
    '