module Concerns::Agentable
  extend ActiveSupport::Concern

  def agent(user: nil, conversation: nil)
    Agents::Agent.new(
      name: agent_name,
      instructions: ->(context) { agent_instructions(context) },
      tools: agent_tools(user: user, conversation: conversation),
      model: agent_model,
      temperature: temperature.to_f || 0.7,
      response_schema: agent_response_schema
    )
  end

  def agent_instructions(context = nil)
    enhanced_context = prompt_context

    if context
      state = context.context[:state] || {}
      conversation_data = state[:conversation] || {}
      contact_data = state[:contact] || {}
      enhanced_context = enhanced_context.merge(
        conversation: conversation_data,
        contact: contact_data
      )
    end

    rendered = Captain::PromptRenderer.render(template_name, enhanced_context.with_indifferent_access)
    return rendered unless respond_to?(:account) && account.present?

    Captain::MediaInterpolationService.new(account: account).interpolate(rendered)
  end

  private

  def agent_name
    raise NotImplementedError, "#{self.class} must implement agent_name"
  end

  def template_name
    self.class.name.demodulize.underscore
  end

  def agent_tools
    []  # Default implementation, override if needed
  end

  def agent_model
    InstallationConfig.find_by(name: 'CAPTAIN_OPEN_AI_MODEL')&.value.presence || LlmConstants::DEFAULT_MODEL
  end

  def agent_response_schema
    Captain::ResponseSchema
  end

  def prompt_context
    raise NotImplementedError, "#{self.class} must implement prompt_context"
  end
end
