#!/usr/bin/env ruby
# frozen_string_literal: true

# SPDX-License-Identifier: GPL-3.0-only
# Copyright (C) 2026 Hugo Antonio Sepulveda Manriquez / NeatNerds
#
# varuna-events-tail — tail the Varuna engine event log with optional filter.
#
# Usage:
#   varuna-events-tail [options]
#
# Options:
#   --filter=REGEX    Only emit events whose +event+ field matches REGEX.
#                     Example: --filter='^autoqueue\.' for the autoqueue subset.
#   --path=PATH       Override the default event log path.
#                     (Default: $XDG_STATE_HOME/varuna/events/engine-events.jsonl)
#   --from-start      Replay events from the beginning of the file before
#                     watching for new ones. Default is to start at EOF.
#   --interval=N      Polling interval in seconds (default: 1).
#   --once            Do one read pass and exit (useful with --from-start
#                     for batch consumption / Monitor MCP sidecar mode).
#   --help            Print this message and exit.
#
# Output:
#   Each matching event is printed as one JSON line to stdout, suitable for
#   piping to jq or Monitor MCP consumers.
#
# Exit codes:
#   0   — normal exit (only with --once)
#   1   — invalid argument
#   130 — SIGINT (Ctrl-C)

require 'json'
require 'optparse'

$LOAD_PATH.unshift(File.expand_path('../lib', __dir__))
require 'varuna/telemetry/jsonl_emitter'
require 'varuna/telemetry/event_tail'

options = {
  path: Varuna::Telemetry::EventTail::DEFAULT_PATH,
  filter: nil,
  from_start: false,
  interval: 1,
  once: false
}

parser = OptionParser.new do |opts|
  opts.banner = 'Usage: varuna-events-tail [options]'
  opts.on('--filter=REGEX', 'Event-name filter regex') { |r| options[:filter] = Regexp.new(r) }
  opts.on('--path=PATH',    'Override event log path') { |p| options[:path] = p }
  opts.on('--from-start',   'Replay from beginning')   { options[:from_start] = true }
  opts.on('--interval=N',   'Polling interval (s)')    { |n| options[:interval] = Float(n) }
  opts.on('--once',         'One pass; do not loop')   { options[:once] = true }
  opts.on('--help',         'Show this message')       do
    puts opts
    exit 0
  end
end

begin
  parser.parse!
rescue OptionParser::InvalidOption, ArgumentError => e
  warn e.message
  warn parser.help
  exit 1
end

tail = Varuna::Telemetry::EventTail.new(
  path: options[:path],
  event_pattern: options[:filter],
  start_at_end: !options[:from_start]
)

trap('INT') { exit 130 }

flush_events = lambda do
  tail.poll.each { puts JSON.generate(it) }
  $stdout.flush
end

if options[:once]
  flush_events.call
  exit 0
end

loop do
  flush_events.call
  sleep options[:interval]
end
