# *************************************************************************
#
#  Copyright (c) 2025 - Datatailr Inc.
#  All Rights Reserved.
#
#  This file is part of Datatailr and subject to the terms and conditions
#  defined in 'LICENSE.txt'. Unauthorized copying and/or distribution
#  of this file, in parts or full, via any medium is strictly prohibited.
# *************************************************************************

import os
import re
import unicodedata

from datatailr.scheduler.constants import BATCH_JOB_ARGUMENTS
from datatailr.tag import get_tag


def get_available_env_args():
    """
    Get the available environment variables for batch job arguments.

    This function retrieves the environment variables that match the keys defined in DATATAILR_BATCH_JOB_ARGUMENTS.

    Returns:
        dict: A dictionary of available environment variables for batch jobs.
    """
    available_args = {}
    for key, value in os.environ.items():
        arg_key = key.replace("DATATAILR_BATCH_ARG_", "").lower()
        if arg_key in BATCH_JOB_ARGUMENTS:
            available_args[arg_key] = value
    return available_args


def normalize_name(name: str) -> str:
    """
    Normalize a name by converting it to lowercase, removing non unicode characters, and replacing spaces with underscores.

    Args:
        name (str): The name to normalize.

    Returns:
        str: The normalized name.
    """
    name = unicodedata.normalize("NFKC", name).lower()
    return re.sub(r"[^0-9a-z]+", "-", name).strip("-")


def get_base_url() -> str:
    """
    Get the job scheduler URL from environment variables.
    Returns:
        str: The job scheduler URL or an empty string if not set.
    """
    hostname = get_tag("public_hostname", cached=True)
    domain = get_tag("public_domain", cached=True)
    if hostname and domain:
        return f"https://{hostname}.{domain}"
    return ""
