# frozen_string_literal: true

# 任务执行数据加载器
# 负责一次性批量加载任务执行所需的数据，避免多次数据库查询
class TaskExecutionDataLoader
  def initialize(task_info)
    @task_info = task_info
    @devices_hash = {}
    @scripts_hash = {}
  end

  # 执行批量加载
  def load!
    load_devices
    load_scripts
    self
  end

  # 获取设备（按ID）
  def get_device(device_id)
    @devices_hash[device_id]
  end

  # 获取脚本（按ID）
  def get_script(script_id)
    @scripts_hash[script_id.to_s]
  end

  # 获取所有设备Hash
  def devices_hash
    @devices_hash
  end

  # 获取所有脚本Hash
  def scripts_hash
    @scripts_hash
  end

  private

  # 批量加载设备
  def load_devices
    device_ids = extract_device_ids
    return if device_ids.empty?

    # 一次性查询所有需要的设备
    devices = LocalDevice.where(id: device_ids).all
    @devices_hash = devices.each_with_object({}) do |device, hash|
      hash[device.id] = device
    end
  end

  # 批量加载脚本
  def load_scripts
    script_ids = extract_script_ids
    return if script_ids.empty?

    # 一次性查询所有需要的脚本
    scripts = CachedScript.where(id: script_ids).all
    @scripts_hash = scripts.each_with_object({}) do |script, hash|
      hash[script.id] = script
    end
  end

  # 从task_info中提取所有设备ID
  def extract_device_ids
    devices = @task_info['devices'] || @task_info[:devices] || []
    devices.map do |device_data|
      device_data['id'] || device_data[:id]
    end.compact.uniq
  end

  # 从task_info中提取所有脚本ID
  def extract_script_ids
    scripts = @task_info['scripts'] || @task_info[:scripts] || []
    scripts.map do |script_data|
      script_data['id'] || script_data[:id]
    end.compact.uniq
  end
end
