# frozen_string_literal: true

# Insights Reports
class InsightsReportsController < ApplicationController
  before_action :set_insights_report
  before_action :set_ancestors

  include ExcelSanitizable

  def generate
    report_metadata = {}

    report_metadata[:question_ids] = @insights_report.question_ids
    report_metadata[:report_id] = @insights_report.id
    report_metadata[:respondent_category_id] = @respondent_category.id
    report_metadata[:llm_model] = @insights_report.llm_model

    if @insights_report.respondents.empty?
      redirect_to insight_reports_project_respondent_category_path(@project, @respondent_category),
                  alert: "Cannot generate insights. No respondents."
    else
      @insights_report.update!(questions_updated: false)

      @insights_report.respondents.each do |respondent|
        report_metadata[:respondent_id] = respondent.id
        report_metadata[:transcript_type] = respondent.transcript_file_name.nil? ? "whisper" : "manual"
        report_metadata[:transcript_version] = 2
        VectorAnalysisJob.perform_later(metadata: report_metadata, user_id: current_user.id)
      end
      redirect_to insight_reports_project_respondent_category_path(@project, @respondent_category),
                  notice: "Insight Generation Queued."
    end
  end

  def csv
    @respondents = Respondent.includes(:interview_insights).joins(:interview_insights).where(interview_insights: { insights_report_id: @insights_report.id }).order(:first_name).distinct

    rows = []
    summary_rows = []
    aggregate_rows = []

    header_row = ["Question"]
    aggregate_header_row = %w[Question Summary]

    require "csv"
    @respondents.each do |respondent|
      header_row << respondent.name
    end
    rows << header_row
    summary_rows << header_row
    aggregate_rows << aggregate_header_row

    @insights_report.interview_questions.includes(:insight_summaries).find_each do |question|
      question_row = []
      summary_row = []
      aggregate_summary_row = []

      question_row << sanitize_and_truncate_for_excel(question.question)

      summary_row << sanitize_and_truncate_for_excel(question.question)

      aggregate_summary_row << sanitize_and_truncate_for_excel(question.question)
      aggregate_summary_row << sanitize_and_truncate_for_excel(question.insight_summaries.select { |s| s.groupable == @insights_report }.last&.summary)

      @respondents.each do |r|
        insight = r.interview_insights.select do |x|
          x.interview_question_id == question.id && x.insights_report_id == @insights_report.id
        end.last

        if insight
          question_row << sanitize_and_truncate_for_excel("\"#{insight.sources}\"")
          summary_row << sanitize_and_truncate_for_excel(insight.ai_summary)
        else
          question_row << " NOT FOUND "
          summary_row << " NOT FOUND "
        end
      end
      rows << question_row
      summary_rows << summary_row
      aggregate_rows << aggregate_summary_row
    end

    require "axlsx"
    p = Axlsx::Package.new
    p.workbook.add_worksheet(name: "Insights") do |sheet|
      wrap_text_style = sheet.styles.add_style(alignment: { wrap_text: true, vertical: :top })
      rows.each do |row|
        sheet.add_row row, style: wrap_text_style
      end

      # Set column widths
      sheet.column_widths 30, 100
    end

    p.workbook.add_worksheet(name: "Insights Summaries") do |sheet|
      wrap_text_style = sheet.styles.add_style(alignment: { wrap_text: true, vertical: :top })
      summary_rows.each do |row|
        sheet.add_row row, style: wrap_text_style
      end

      # Set column widths
      sheet.column_widths 30, 100
    end

    p.workbook.add_worksheet(name: "Aggregate Summaries") do |sheet|
      wrap_text_style = sheet.styles.add_style(alignment: { wrap_text: true, vertical: :top })
      aggregate_rows.each do |row|
        sheet.add_row row, style: wrap_text_style
      end

      # Set column widths
      sheet.column_widths 30, 100
    end

    excel_data = p.to_stream.read

    send_data excel_data, filename: "#{@insights_report.name.parameterize}_insight_report.xlsx",
                          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  end

  def show; end

  def generate_summary
    InsightsReportSummaryJob.perform_later(
      metadata: { insights_report_id: params[:id].to_i,
                  respondent_category_id: @respondent_category.id }, user_id: current_user.id
    )
    redirect_to insight_reports_project_respondent_category_path(@project, @respondent_category),
                notice: "Insight Report Summarization Queued"
  end

  def delete_report
    report = InsightsReport.find(params[:id])
    report&.destroy
    redirect_to insight_reports_project_respondent_category_path(@project, @respondent_category), notice: "Insights Report Successfully Deleted"
  end

  private

  def set_ancestors
    @project = Project.find(params[:project_id])
    @respondent_category = RespondentCategory.find(params[:respondent_category_id])
  end

  # Use callbacks to share common setup or constraints between actions.
  def set_insights_report
    @insights_report = InsightsReport.find(params[:id])
  end
end
