import { useBranchingQuiz } from "./FlowControlLogic/useBranchingQuiz";
import { useLinearQuiz } from "./FlowControlLogic/useLinearQuiz";
import { useAIQuiz } from "./FlowControlLogic/useAIQuiz";
import { Status } from "@/model/settingsData";
import { useQuizStore } from "@/stores/useQuizStore";

interface StatusData {
  status: Status;
  haveRoot: string | null;
}

// выбор способа управления в зависимости от статуса
let cachedManager: () => ReturnType<typeof useLinearQuiz>;
export let statusOfQuiz: "line" | "branch" | "ai";
let isInitialized = false;

function analyicStatus({ status, haveRoot }: StatusData) {
  if (status === "ai") {
    statusOfQuiz = "ai";
    return;
  }
  if (status === "start") {
    // Если есть ветвление, то settings.cfg.haveRoot будет заполнен
    if (haveRoot) statusOfQuiz = "branch";
    else statusOfQuiz = "line";
    return;
  }
  throw new Error("quiz is inactive");
}

export const initDataManager = (data: StatusData) => {
  analyicStatus(data);
  switch (statusOfQuiz) {
    case "line":
      cachedManager = useLinearQuiz;
      break;
    case "branch":
      cachedManager = useBranchingQuiz;
      break;
    case "ai":
      cachedManager = useAIQuiz;
      break;
  }
  isInitialized = true;
};

// Главный хук (интерфейс для потребителей)
export const useQuestionFlowControl = () => {
  if (!cachedManager || !isInitialized) {
    // Попытка автоматической инициализации на основе текущих настроек
    const { settings } = useQuizStore.getState();
    if (settings && settings.status) {
      initDataManager({
        status: settings.status,
        haveRoot: settings.cfg.haveRoot,
      });
    } else {
      throw new Error("DataManager not initialized! Call initDataManager() first.");
    }
  }
  return cachedManager();
};

// Функция для сброса состояния (полезна для HMR)
export const resetDataManager = () => {
  cachedManager = null as any;
  isInitialized = false;
  statusOfQuiz = null as any;
};
