import json
from pathlib import Path
from typing import Any, Dict, Optional

# keep the module-level definitions and type hints
PROJECT_DIRECTORY: Optional[str] = None
BHE_DOMAIN: Optional[str] = None
BHE_PORT: Optional[int] = None
BHE_TOKEN_ID: Optional[str] = None
BHE_TOKEN_KEY: Optional[str] = None

DEFAULT_KEYS = (
    "PROJECT_DIRECTORY",
    "BHE_DOMAIN",
    "BHE_PORT",
    "BHE_TOKEN_ID",
    "BHE_TOKEN_KEY",
)

def load_variables() -> Dict[str, Optional[Any]]:
    """
    Load configuration from a JSON file, set module globals, and return a dict.
    Empty strings become None. BHE_PORT will be converted to int when possible.
    """
    global PROJECT_DIRECTORY, BHE_DOMAIN, BHE_PORT, BHE_TOKEN_ID, BHE_TOKEN_KEY

    p = Path(__file__).parent/"config/config.json"
  
    data = json.loads(p.read_text(encoding="utf-8"))

    loaded: Dict[str, Optional[Any]] = {}
    for key in DEFAULT_KEYS:
        val = data.get(key)
        if isinstance(val, str) and val.strip() == "":
            val = None
        if key == "BHE_PORT" and val is not None:
            try:
                val = int(val)
            except (TypeError, ValueError):
                pass
        loaded[key] = val

    PROJECT_DIRECTORY = loaded["PROJECT_DIRECTORY"]
    BHE_DOMAIN = loaded["BHE_DOMAIN"]
    BHE_PORT = loaded["BHE_PORT"]
    BHE_TOKEN_ID = loaded["BHE_TOKEN_ID"]
    BHE_TOKEN_KEY = loaded["BHE_TOKEN_KEY"]

    return loaded
