# Copyright (C) 2012-2026 Zammad Foundation, https://zammad-foundation.org/

##
# AI::Agent is a model that represents an AI agent with different strcutre parts:
#
# Definition:
#
# `role_description``: 'You have the role of doing something.',
# `instruction``: '- You should do this.
# - You should the other things.
# - ...',
# `instruction_context`: {
#    object_attributes: {
#      group_id: { '3' => 'Support team for technical issues', '4' => 'Sales team for customer inquiries' },
#      state_id: { '1' => 'New tickets awaiting assignment', '2' => 'Open tickets being worked on' },
#      custom_treeselect: { 'Category 1' => 'Main category for general issues', 'Category 1::Sub 1' => 'Subcategory for specific problems' },
#    }
#  }, // Informations which are added to the instructions (e.g. relevant group information for ticket group dispatching).
# `entity_context`: {
#    object_attributes: ['title', 'priority_id'], // All attributes of the object are possible.
#    articles: 'first|last|all', // The last article (current trigger article) or all articles of the object.
#  },
#  `result_structure`: {
#    group_id: 'integer',
#    is_real_question: 'boolean',
#  }, // JSON-Result structure is optional, it can also only be text.
#
# Action definition:
#
# The `ai_agent_result.example` will be replaced with the value from the AI service call, but also static values
# are possible.
#
# `mapping`: {
#   'ticket.group_id' => {
#     'value' => '#{ai_agent_result.group_id}'
#   },
# }, // Mapping of the result to the object attributes in perform changes syntax style.
#
# `conditions`: [
#   {
#     condition: {
#       is_real_question: false
#     },
#     mapping: {
#       'ticket.state' => {
#         'value' => 'closed'
#       },
#     }
#   }
# ], // Conditions are optional, they are used to check if the mapping should be executed.
#
# The mappings from the condition will be added to the general mapping and executed together.
#

class AI::Agent < ApplicationModel
  include ChecksHtmlSanitized
  include HasSearchIndexBackend
  include CanSelector
  include CanSearch
  include EnsuresNoRelatedObjects
  include AI::Agent::Assets
  include ChecksClientNotification
  include HasAuditLogs

  PERFORMABLE_PATH = ['ai.ai_agent', 'ai_agent_id'].freeze

  validates :name, presence: true, uniqueness: { case_sensitive: false }
  validates :note, length: { maximum: 250 }
  validates :agent_type, inclusion: { in: AI::Agent::Type.available_types.map { |t| t.name.demodulize }, allow_blank: true }

  sanitized_html :note

  belongs_to :created_by, class_name: 'User'
  belongs_to :updated_by, class_name: 'User'

  ensures_no_related_objects_path(*PERFORMABLE_PATH)

  class << self
    # All active agents referenced by the performable (supports multiple agents per trigger/job).
    def all_from_performable(input)
      where(active: true, id: from_performable_ids(input))
    end

    # Reads the configured agent id(s) from the perform hash. The value was a single
    #   id in the past (single-select) and is an array now, so we normalize to an array.
    #   Ids are cast to integers because they may be stored as integers (created via
    #   API/seeds) or strings (created via the UI); normalizing avoids treating a mere
    #   type change as a real change (spurious touches).
    def from_performable_ids(input)
      data = input.respond_to?(:perform) ? input.perform : input
      Array.wrap(data&.dig(*PERFORMABLE_PATH)).compact_blank.map(&:to_i).uniq
    end

    # Used by ObjectManager::Attribute.attribute_to_references_hash to
    # check which attributes cannot be deleted because they are used in AI agents.
    #
    # @return [Hash] a hash with the attribute name as key and the AI agent names as values
    #
    #   {'ticket.custom_textfield' => { 'AI Agent' => ['Test AI Agent', 'Test AI Agent 2'] } }
    #
    def object_attribute_dependencies
      all.each_with_object({}) do |agent, result|
        type = agent.agent_type_object
        next if !type

        deps = type.object_attribute_dependencies
        next if deps.blank?

        deps.each do |dep|
          key = "#{type.object_attribute_object_name.downcase}.#{dep}"
          result[key] ||= { __('AI Agent') => [] }
          result[key][__('AI Agent')] << agent.name
        end
      end
    end
  end

  def execution_definition(context: {})
    return definition if agent_type.blank?

    agent_type_object.execution_definition(context:).deep_stringify_keys.deep_merge(definition)
  end

  def execution_action_definition
    return action_definition if agent_type.blank?

    agent_type_object.execution_action_definition.deep_stringify_keys.deep_merge(action_definition)
  end

  def agent_type_object
    @agent_type_object ||= agent_type_class&.new(
      type_enrichment_data:,
    )
  end

  # Merge the agent type's form-visible defaults into the serialized
  #   `type_enrichment_data` so the legacy edit dialog hydrates fields that
  #   weren't saved at creation time (e.g. `tag_new_rules` once `tag_new` is
  #   enabled later). Runtime-only `base_type_enrichment_data` stays on the
  #   type object and never leaks into the form.
  def attributes_with_association_ids
    attrs = super
    return attrs if agent_type_class.blank?

    defaults = agent_type_class.new.default_type_enrichment_data.stringify_keys
    attrs['type_enrichment_data'] = defaults.merge(attrs['type_enrichment_data'] || {})
    attrs
  end

  def self.working_on_ticket?(ticket)
    ActiveJobLock
      .exists?(['lock_key LIKE ?', "TriggerAIAgentJob/Ticket/#{ticket.id}/AIAgent/%"])
  end

  # Checks for tickets that are marked as ai_agent_running but have no active AI agent jobs.
  def self.cleanup_orphan_jobs
    Ticket
      .where(ai_agent_running: true)
      .find_each do
        is_working = AI::Agent.working_on_ticket?(it)

        next if is_working

        it.update_columns ai_agent_running: false # rubocop:disable Rails/SkipsModelValidations
        it.cache_delete # Clear cache after direct DB update
      end
  end

  private

  def agent_type_class
    return if agent_type.blank?

    "AI::Agent::Type::#{agent_type}".constantize
  end
end
