# frozen_string_literal: true

# Interview Questions
class InterviewQuestion < ApplicationRecord
  acts_as_list scope: :respondent_category_id

  has_many :insight_summaries, dependent: :destroy
  has_many :interview_insights, dependent: :destroy
  belongs_to :respondent_category, optional: true
  has_one :project, through: :respondent_category

  has_many :question_sections, dependent: :destroy
  has_many :master_sections, through: :question_sections

  # Keep this for now until the old column is completely dropped in a future PR
  belongs_to :master_section, optional: true

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

  def self.generate_questions_with_dg(dg_text, respondent_category_id)
    model_map = FeatureModelMap.find_by(feature_name: "DG_QUERIES_GENERATION")
    chat = RubyLLM.chat(provider: model_map.provider, model: model_map.llm_model_name)

    system_prompt = <<~SYSTEM_PROMPT
      You are a market research analyst. You will be given a Discussion Guide (DG) which you will use as reference to create questions.
      Write the questions in such a way that when these questions and a transcript is given to an LLM, it can easily find the answers to
      the questions in the transcript.
      A transcript usually consists of an intervierwer and a respondent (sometimes multiple respondents).

      Return ONLY valid JSON with only 1 key "results", and an array of string values.
      Example response: {"results": ["Question 1", "Question 2"]}
    SYSTEM_PROMPT

    prompt = <<~PROMPT
      This is the DG:
      ```
      #{dg_text}
      ```
    PROMPT

    chat.with_instructions(system_prompt)
    response = chat.ask(prompt)

    json_match = response.content.match(/\{.*\}/m)
    unless json_match
      Rails.logger.error("No JSON found in LLM response")
      return
    end

    begin
      parsed_json = JSON.parse(json_match[0])
    rescue JSON::ParserError => e
      Rails.logger.error("Failed to parse JSON: #{e.message}")
      return
    end

    questions = parsed_json["results"]

    unless questions.is_a?(Array)
      Rails.logger.error("LLM response 'results' is not a valid array")
      return
    end

    questions.each do |question|
      InterviewQuestion.create!(question:, respondent_category_id:)
    end

    task = SystemTask.where(task_type: "GenerateQueriesDG")
                     .where("metadata @> ?", { respondent_category_id: }.to_json)
                     .last

    return unless task

    task.update(status: "complete", running: false)

    respondent_category = RespondentCategory.find(respondent_category_id)

    # 1. Replace the button back to its active state
    Turbo::StreamsChannel.broadcast_replace_to(
      respondent_category, "tasks",
      target: "dg_queries_import_action_#{respondent_category.id}",
      partial: "interview_questions/dg_queries_import_button",
      locals: { respondent_category:, queries_generating: false }
    )

    # 2. Append the JS trigger to tell Vue to fetch the new data
    Turbo::StreamsChannel.broadcast_append_to(
      respondent_category, "tasks",
      target: "dg_queries_import_action_#{respondent_category.id}",
      html: "<script>window.dispatchEvent(new CustomEvent('dg-queries-generated'));</script>"
    )

    SystemTask.execute_next_task!(task_class: task.task_class)
  end

  def generate_insights
    formatted_answers = ""
    interview_insights.each_with_index do |insight, i|
      formatted_answers << "#{i + 1}) #{JSON.parse(insight.sources).first}\n\n"
    end
    json = { answers: formatted_answers, question: { id:, text: question } }.to_json
    File.open("#{SCRIPT_PATH}/insights_#{id}.json", "w") { |f| f.write json }
    require "shellwords"
    params_file = "#{SCRIPT_PATH}/insights_#{id}.json"
    command = "#{SCRIPT_PATH}/insights.sh #{Shellwords.escape(params_file)}"
    Rails.logger.fatal command
    results = `#{command}`
    Rails.logger.fatal "Results received: #{results}"
    json_data = results.split("===RESULT===").last.strip
    json = JSON.parse(json_data)
    InsightSummary.create!(interview_question_id: id, summary: json["data"]["response"]["insight"])
  end
end
