getAssistant method

Future<void> getAssistant()

Implementation

Future<void> getAssistant() async {
  try {
    isLoadingAssistant.value = true;
    final String id = pupauConfig?.assistantId ?? "";
    if (id.isEmpty) return;
    assistant.value = await AssistantService.getAssistant(id, isMarketplace);
    _preserveInitialWelcomeIfAssistantEmpty();
    assistant.refresh();
    if (assistant.value == null) {
      hasApiError.value = true;
      _updateBootStatus(BootState.error);
      update();
      return;
    }
    // Keep PupauAssistantsController cache in sync so future openings (and
    // applyCachedAssistantIfAvailable) have the latest welcomeMessage and
    // other fields without waiting on the network again.
    if (Get.isRegistered<PupauAssistantsController>()) {
      final PupauAssistantsController assistantsController =
          Get.find<PupauAssistantsController>();
      final Assistant? current = assistant.value;
      if (current == null) return;
      final int existingIndex = assistantsController.assistants.indexWhere(
        (a) => a.id == current.id && a.type == current.type,
      );
      if (existingIndex >= 0) {
        assistantsController.assistants[existingIndex] = current;
        assistantsController.assistants.refresh();
        assistantsController.update();
      } else {
        assistantsController.assistants.add(current);
        assistantsController.assistants.refresh();
        assistantsController.update();
      }
    }
    setAssistantSettings();
    // Boot status will be set to OK in initChatController after successful initialization
  } catch (e, stackTrace) {
    _updateBootStatus(BootState.error);
    PupauEventService.instance.emitPupauEvent(
      PupauEvent(
        type: UpdateConversationType.error,
        payload: {
          "error": "Error getting assistant: ${e.toString()}",
          "errorType": e.runtimeType.toString(),
          "stackTrace": stackTrace.toString(),
          "assistantId": assistantId,
          "isMarketplace": isMarketplace,
          "assistantType": assistant.value?.type ?? AssistantType.assistant,
          "configExists": pupauConfig != null,
          "configAssistantId": pupauConfig?.assistantId,
        },
      ),
    );
  } finally {
    isLoadingAssistant.value = false;
  }
}