# frozen_string_literal: true

# Monkey-patch ruby_llm 1.12.1 VertexAI provider for compatibility with
# googleauth < 1.15 and Ruby 3 keyword argument semantics.
#
# Fixes two production errors:
#   1. NameError: uninitialized constant Google::Auth::AuthorizationError
#      (the constant does not exist; use Signet::AuthorizationError instead)
#   2. TypeError in Signet::OAuth2::Client#scope=: Expected Array or String, got Hash
#      (get_application_default expects a positional Array, not a keyword argument)

module RubyLLM
  module Providers
    # Patch for ruby_llm 1.12.1 compatibility with googleauth < 1.15
    class VertexAI < Gemini
      def headers
        if defined?(VCR) && !VCR.current_cassette.recording?
          { "Authorization" => "Bearer test-token" }
        else
          initialize_authorizer unless @authorizer
          @authorizer.apply({})
        end
      rescue Signet::AuthorizationError => e
        raise UnauthorizedError.new(nil, "Invalid Google Cloud credentials for Vertex AI: #{e.message}")
      end

      private

      def initialize_authorizer
        require "googleauth"
        @authorizer = ::Google::Auth.get_application_default(
          ["https://www.googleapis.com/auth/cloud-platform",
           "https://www.googleapis.com/auth/generative-language.retriever"]
        )
      rescue LoadError
        raise Error,
              "The googleauth gem is required for Vertex AI. Please add it to your Gemfile: gem \"googleauth\""
      end
    end
  end
end
