# typed: strict
module Tasks
  class UserInterruptMonitor
    extend T::Sig

    sig { params(log_sink: T.any(IO, StringIO)).void }
    def initialize(log_sink: $stderr)
      @log_sink = log_sink
      @interrupted = T.let(false, T::Boolean)

      # Handle Ctrl+C (SIGINT) for clean shutdown
      Signal.trap("INT") do
        @log_sink.puts "\nReceived interrupt signal. Finishing current batch and saving progress..."
        @interrupted = true
        Signal.trap("INT", "DEFAULT")
      end

      # Handle SIGTERM for clean shutdown (useful for systemd/docker)
      Signal.trap("TERM") do
        @log_sink.puts "\nReceived termination signal. Finishing current batch and saving progress..."
        @interrupted = true
        Signal.trap("TERM", "DEFAULT")
      end
    end

    sig { returns(T::Boolean) }
    def interrupted?
      @interrupted
    end
  end
end
