"""
Helpers for loading environment variables used by Django startup scripts.
"""

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent
DEFAULT_APP_ENV_FILE = BASE_DIR / '.app_env'


def _strip_optional_quotes(value):
    """
    Removes matching wrapping quotes from a value.
    :param value: The raw value
    :return: Unquoted value
    """
    if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):
        return value[1:-1]

    return value


def load_app_env(env_file=DEFAULT_APP_ENV_FILE):
    """
    Loads variables from a .app_env file into os.environ.

    Existing environment variables are preserved so shell-provided values win.
    Supports lines in the forms KEY=value and export KEY=value.

    :param env_file: Optional path to an env file
    """
    try:
        with open(Path(env_file), encoding='utf-8') as file:
            for raw_line in file:
                line = raw_line.strip()

                if not line or line.startswith('#'):
                    continue

                if line.startswith('export '):
                    line = line[len('export '):].strip()

                if '=' not in line:
                    continue

                key, value = line.split('=', 1)
                key = key.strip()
                value = _strip_optional_quotes(value.strip())

                if not key:
                    continue

                os.environ.setdefault(key, value)
    except FileNotFoundError:
        pass
