# frozen_string_literal: true

# 任务完成处理器
# 单一职责：处理任务完成后的状态更新和清理
class TaskFinalizer
  def initialize(state_manager)
    @state_manager = state_manager
  end

  # 完成任务
  # @param execution [LocalTaskExecution] 执行记录对象
  def finalize(execution)
    final_state = @state_manager.get_task(execution.id)
    puts "[TaskFinalizer] Finalizing task, has final_state: #{!final_state.nil?}"

    if final_state
      all_success = all_scripts_successful?(final_state)
      # 更新内存中的状态为完成
      @state_manager.update_task(execution.id, {
        status: all_success ? 'completed' : 'failed',
        progress: 100,
        completed_at: Time.now.iso8601
      })
      # 使用内存中的最终状态来完成任务
      execution.complete_from_memory!(final_state, success: all_success)
    else
      execution.complete!(success: false)
    end

    puts "[TaskFinalizer] 任务执行完成: execution_id=#{execution.id}"
  end

  private

  # 检查是否所有脚本都执行成功
  # @param final_state [Hash] 任务最终状态
  # @return [Boolean]
  def all_scripts_successful?(final_state)
    execution_units = final_state[:execution_units] || {}
    execution_units.each do |device_id, device_unit|
      scripts = device_unit['scripts'] || device_unit[:scripts] || {}
      scripts.each do |script_id, script_info|
        return false if script_info['status'] != 'completed'
      end
    end
    true
  end
end
