# frozen_string_literal: true

# Interview Insights
class InterviewInsight < ApplicationRecord
  HOST = "http://localhost"
  SCRIPT_PATH = "/home/fareesh/scripts/sprint"

  belongs_to :respondent
  belongs_to :interview_question
  belongs_to :insights_report, optional: true
  belongs_to :master_section, optional: true

  def ai_summary_markdown
    ApplicationController.helpers.markdown_render(ai_summary)
  end

  def cleaned_sources
    json_sources = begin
      JSON.parse(sources)
    rescue StandardError
      []
    end
    c_sources = []
    # Rails.logger.fatal "There are #{json_sources.size} sources"
    json_sources.each do |source|
      result = []
      lines = source.split("\n")
      # Rails.logger.fatal "There are #{lines.size} lines"
      lines.each do |line|
        result << line if line.strip != "" && !result.include?(line)
      end
      c_sources << result
    end
    c_sources
  end

  def surrounding_transcript
    if respondent.whisper_transcript
      full_text = respondent.whisper_transcript.verbose_to_text.gsub("  ", " ")
      index = transcript_index
      full_text[index - 500..index + 500]
    else
      ""
    end
  end

  def transcript_index
    return unless respondent.whisper_transcript

    full_text = respondent.whisper_transcript.verbose_to_text.gsub("  ", " ")
    cs = begin
      cleaned_sources.last&.join("\n\n")&.[](-100..-1)&.gsub("  ", " ")
    rescue StandardError
      nil
    end
    begin
      full_text&.index(cs)
    rescue StandardError
      nil
    end
  end

  def ai_summarize(language: :en)
    model_map = FeatureModelMap.find_by(feature_name: "QUERY_INSIGHT_SUMMARIES")
    return unless model_map

    instruction = Instruction.find_by(key: "INDIVIDUAL_INSIGHT_SUMMARIES")
    system_prompt = instruction.system_prompt
    language_prompt = " The language to be used for the summarization is #{Respondent::LANGUAGES.transform_values(&:titleize)[language]}"
    system_prompt.concat(language_prompt)
    prompt = "#{instruction.prompt} <transcript-section>#{sources}</transcript-section>"

    # Rails.logger.debug prompt

    response = LanguageModel.send_with_system_prompt_v2(prompt, system_prompt, language_model: model_map.llm_model_name, provider: model_map.provider)
    return unless response[:status] == "ok"

    self.ai_summary = response[:data]
    save
  end

  def self.write_parameters(respondent:, question_ids:, respondent_category_id:, insights_report_id:, whisper: false, version: 2, llm_model: "gpt-4o-mini")
    system_prompt = Instruction.find_by(key: "INSIGHTS").system_prompt
    if whisper
      # Write our transcript out to a file:
      if version == 1
        text = respondent.whisper_transcript.text
      elsif version == 2
        text = respondent.whisper_transcript.verbose_to_text
      end

      path = "/tmp/whisper_#{respondent.id}.txt"
      File.open(path, "w") { |f| f.write text }

      parameters = {
        questions: respondent.questions_json(respondent_category_id:, question_ids:),
        respondent_id: respondent.id,
        insights_report_id:,
        system_prompt:,
        version:,
        whisper:,
        llm_model:,
        filename: path,
        submission_endpoint: "#{HOST}/api/save_response"
      }
    else
      # If the docx was translated using the translation feature
      docx_transcript = respondent.docx_transcript
      if docx_transcript.translated
        text = docx_transcript.verbose_to_text
        path = "/tmp/translated_#{respondent.id}.txt"
        File.open(path, "w") { |f| f.write text }
        download_path = path
      else
        downloaded_file_name = File.basename(respondent.transcript.path)
        download_path = "/tmp/#{downloaded_file_name}"
        `wget "#{respondent.transcript.url(:original, timestamp: false)}" -O "#{download_path}"`
      end
      parameters = {
        questions: respondent.questions_json(respondent_category_id:, question_ids:),
        respondent_id: respondent.id,
        version:,
        whisper:,
        system_prompt:,
        llm_model:,
        insights_report_id:,
        filename: download_path,
        submission_endpoint: "#{HOST}/api/save_response"
      }
    end
    input_path = "#{SCRIPT_PATH}/parameters_#{respondent.id}.json"
    File.open(input_path, "w") { |f| f.write(parameters.to_json) }
    Rails.logger.fatal("Wrote Parameters")
    input_path
  end

  def self.generate_two_stage(respondent:, question_ids:, respondent_category_id:, insights_report_id:, whisper: false, version: 2, llm_model: "gpt-4o-mini")
    # This writes the parameters to the script path as a json file
    Rails.logger.fatal "Writing Parameters"
    Rails.logger.fatal "REPORT ID: #{insights_report_id}"
    InterviewInsight.write_parameters(
      respondent:,
      whisper:,
      version:,
      respondent_category_id:,
      question_ids:,
      insights_report_id:,
      llm_model:
    )
    require "shellwords"
    params_file = "#{SCRIPT_PATH}/parameters_#{respondent.id}.json"

    command = "#{SCRIPT_PATH}/two_stage.sh #{Shellwords.escape(params_file)}"
    Rails.logger.fatal "Executing: #{command}"
    `#{command}`
  end
end
