# app/controllers/assistants_controller.rb
class AssistantsController < ApplicationController
  def index
    @assistants = if current_user.role == "admin"
                    Assistant.where(custom: true).order(created_at: :desc)
                  else
                    current_user.organization.assistants.where(custom: true).order(created_at: :desc)
                  end
  end

  def assistant_v2
    @assistant = if current_user.role == "admin"
                   Assistant.find(params[:id])
                 else
                   current_user.organization.assistants.find(params[:id])
                 end

    @conversations = @assistant.assistant_conversations
                               .joins(:user)
                               .where(users: { organization_id: current_user.organization_id })
                               .order(created_at: :desc)

    @conversation = if params[:conversation_id]
                      @conversations.find(params[:conversation_id])
                    else
                      @conversations.first || @assistant.assistant_conversations.create!(user: current_user)
                    end
    gon.conversationId = @conversation.id
  end

  def scopes_tree
    projects = if current_user.role == "admin"
                 Project.includes(:respondent_categories).order(:title)
               else
                 current_user.organization.projects.includes(:respondent_categories).order(:title)
               end

    tree = projects.map do |project|
      {
        id: project.id,
        title: project.title,
        categories: project.respondent_categories.map do |category|
          { id: category.id, name: category.name }
        end
      }
    end

    render json: tree
  end

  def assistant_status
    @assistant = if current_user.role == "admin"
                   Assistant.find(params[:id])
                 else
                   current_user.organization.assistants.find(params[:id])
                 end

    if params[:task_id].present?
      # Flow 1: We are explicitly tracking a task (Post-creation redirect)
      @task = SystemTask.find(params[:task_id])
      if @task.progress >= 100 || @task.status == "complete"
        redirect_to assistant_v2_assistant_path(@assistant)
        nil
      end
    else
      # Flow 2: User clicked "Chat" from the index page. Check for running tasks.
      @task = SystemTask.where(task_type: "GenerateAssistantV2", status: %w[running queued])
                        .where("metadata @> ?", { assistant_id: @assistant.id }.to_json).last

      if @task
        # A generation task is currently running, redirect to include the task_id in the URL
        redirect_to assistant_status_assistant_path(@assistant, task_id: @task.id)
      else
        # Assistant is ready (no active tasks). Go straight to chat.
        redirect_to assistant_v2_assistant_path(@assistant)
      end
      nil
    end
  end

  def create
    ActiveRecord::Base.transaction do
      @assistant = Assistant.create!(
        name: params[:name],
        organization: current_user.organization,
        custom: true
      )

      if params[:scopes].present?
        params[:scopes].each do |scope|
          AssistantScope.create!(
            assistant: @assistant,
            scopable_type: scope[:type],
            scopable_id: scope[:id]
          )
        end
      end
    end

    status = SystemTask.where(task_class: "LLM", running: true).count.positive? ? "queued" : "running"
    running = status == "running"

    @task = SystemTask.create!(
      task_type: "GenerateAssistantV2",
      task_class: "LLM",
      user_id: current_user.id,
      running: running,
      status: status,
      metadata: { assistant_id: @assistant.id }
    )

    ExecuteGenerateAssistantJob.perform_later(@task.id, current_user.id) if running

    flash[:notice] = "Generating custom assistant. The process takes time, please be patient."

    render json: {
      success: true,
      redirect_url: assistant_status_assistant_path(@assistant, task_id: @task.id)
    }, status: :created
  rescue StandardError => e
    flash[:alert] = "Custom assistant could not be created. Please contact the team."

    render json: { success: false, message: e.message }, status: :unprocessable_entity
  end

  def destroy
    @assistant = if current_user.role == "admin"
                   Assistant.find(params[:id])
                 else
                   current_user.organization.assistants.find(params[:id])
                 end

    @assistant.destroy!

    redirect_to assistants_path, notice: "Custom assistant was successfully deleted."
  end
end
