import os

from .logger import LogHandler, ElasticLoggerConfig, create_logger

logger = None


def init_logger(config: ElasticLoggerConfig = None) -> None:
    """
    Initializes the global logger instance.

    :param config: ElasticLoggerConfig (optional). If not provided, it uses environment variables.
    """
    global logger  # Make sure the global variable is updated

    if config is None:
        hosts = os.getenv("ELASTICSEARCH_HOSTS")
        api_key = os.getenv("ELASTICSEARCH_API_KEY")
        index_name = os.getenv("ELASTICSEARCH_INDEX")
        application_name = os.getenv("APPLICATION_NAME")
        cert_path = os.getenv("ELASTICSEARCH_CERT_PATH", "./logger/elasticsearch-ca.crt")

        if not all([hosts, api_key, index_name, application_name]):
            raise ValueError("Missing required environment variables (ELASTICSEARCH_*)")

        config = ElasticLoggerConfig(
            hosts=hosts,
            api_key=api_key,
            index_name=index_name,
            application_name=application_name,
            cert_path=cert_path
        )

    logger = create_logger(config)  # Assign to global variable


try:
    init_logger()
except ValueError:
    pass

__all__ = ["logger", "init_logger", "ElasticLoggerConfig", "LogHandler"]
