class QuantifiableQuestion < ApplicationRecord
  belongs_to :respondent_category
  has_many :respondents, through: :respondent_category

  SCRIPT_PATH = "/home/fareesh/scripts/sprint"

  def execute_script!
    json = { question_id: id, question:, respondent_ids: respondents.pluck(:id),
             submission_endpoint: "https://analysis.sprintstudio.ai/map_reduce_answers/#{id}" }.to_json
    File.open("#{SCRIPT_PATH}/qq_#{id}.json", "w") { |f| f.write json }
    require "shellwords"
    params_file = "#{SCRIPT_PATH}/qq_#{id}.json"

    command = "#{SCRIPT_PATH}/map_reduce.sh #{Shellwords.escape(params_file)}"
    Rails.logger.fatal command

    results = `#{command}`
  end

  def queue_task(user)
    AskQuantifiableQuestionJob.perform_later(metadata: { quantifiable_question_id: id }, user_id: user.id)
  end
end
