class InsightResponse < ApplicationRecord
  belongs_to :respondent

  def generate_insights
    json["data"]["responses"].each do |answer|
      Rails.logger.debug "Answer is #{answer}"
      question = InterviewQuestion.find(answer["id"])
      Rails.logger.debug "The question is - #{question.id}"

      if !answer["response"].instance_of?(Hash)
        response = begin
          JSON.parse(answer["response"])
        rescue StandardError
          nil
        end
        if response.nil?
          Rails.logger.debug "Error parsing json for #{question.id}"
          Rails.logger.debug "************************"
          Rails.logger.debug "Answer is #{answer['response']}"
          json_part = answer["response"].split("{")[1..-1].join("")
          json_part = "{#{json_part}"
          Rails.logger.debug "New Answer is #{json_part}"
          Rails.logger.debug "************************"
          response = begin
            JSON.parse(json_part)
          rescue StandardError
            nil
          end
        end
      else
        response = answer["response"]
      end
      response = { "answer": "Error with answer", "sources": [] } if response.nil?
      response["sources"] = [response["sources"]] unless response["sources"].instance_of? Array

      existing = InterviewInsight.where(respondent:, interview_question: question, whisper_version:, from_whisper:,
                                        insights_report_id:).first

      existing&.destroy

      InterviewInsight.create!(
        respondent:,
        whisper_version:,
        from_whisper:,
        insights_report_id:,
        interview_question: question,
        insight: response["answer"],
        sources: response["sources"]
      )

      begin
        insights_report = InsightsReport.find(insights_report_id)
        completed_tasks = SystemTask.where(task_type: "VectorAnalysis", status: "complete", running: false)
                                    .where("metadata @> ?",
                                           { report_id: insights_report_id,
                                             generation_id: insights_report.generation_id }.to_json).count

        Rails.logger.debug "[INSIGHTS] Checking insight generation completion... "
        Rails.logger.debug "[INSIGHTS] (Respondent count) #{insights_report.respondent_ids.count} == #{completed_tasks + 1} (Completed tasks count)"

        if insights_report.respondent_ids.count == (completed_tasks + 1)
          Rails.logger.debug "[INSIGHTS] ***** INSIGHTS GENERATED FOR REPORT - #{insights_report_id}, Queuing Summary Generation ****"
          user = SystemTask.where(task_type: "VectorAnalysis")
                           .where("metadata @> ?",
                                  { report_id: insights_report_id,
                                    generation_id: insights_report.generation_id }.to_json).last.user
          insights_report.queue_summary_generation(user_id: user.id)
        end
      rescue StandardError => e
        Rails.logger.error "[INSIGHTS] Insights Generation Completion Check Error - #{e.inspect}"
      end
    end
  end
end
