from django.apps import AppConfig
import os
import logging

logger = logging.getLogger(__name__)


class FeedbackConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "feedback"

    def ready(self):
        # This method runs once when the server is ready.
        # We check for the RUN_MAIN environment variable to avoid running this code
        # in the reloader process, which would execute it twice in development.
        if os.environ.get("RUN_MAIN") == "true":
            try:
                from .rag_service import initialize_rag_components

                # It's safer to get env vars inside the ready() method
                # to ensure all settings are loaded.
                mistral_api_key = os.getenv("MISTRAL_API_KEY")
                if not mistral_api_key:
                    logger.error(
                        "MISTRAL_API_KEY is not set. RAG components will not initialize."
                    )
                    return

                # Call the initialization function from your RAG service.
                initialize_rag_components(mistral_api_key)
                logger.info(
                    "RAG components initialization triggered successfully from feedback app."
                )
            except ImportError:
                logger.error(
                    "Could not import RAG components. Ensure 'rag_service.py' exists and is correct."
                )
            except Exception as e:
                logger.error(
                    f"Error during RAG components initialization: {e}", exc_info=True
                )
