"""One shared connection to the MetaTrader 5 terminal (Windows only: the MT5 desktop app must be running)."""
import os

_mt5 = None


def tf_name(tf: str) -> str:
    """'15m' -> 'M15', '1h' -> 'H1', '4h' -> 'H4', '1d' -> 'D1'"""
    n, u = int(tf[:-1]), tf[-1]
    return {"m": "M", "h": "H", "d": "D", "w": "W"}[u] + str(n)


def get_mt5():
    global _mt5
    if _mt5 is not None:
        return _mt5
    try:
        import MetaTrader5 as mt5
    except ImportError as e:
        raise RuntimeError("The MetaTrader5 Python package is missing. Install it with: pip install MetaTrader5 "
                           "(Windows only, and the MT5 app must be installed).") from e
    kw = {}
    if os.environ.get("MT5_PATH"):
        kw["path"] = os.environ["MT5_PATH"]
    if os.environ.get("MT5_LOGIN"):
        kw.update(login=int(os.environ["MT5_LOGIN"]), password=os.environ.get("MT5_PASSWORD", ""),
                  server=os.environ.get("MT5_SERVER", ""))
    if not mt5.initialize(**kw):
        raise RuntimeError(f"MT5 initialize failed: {mt5.last_error()}. Is the MT5 app open and logged in?")
    _mt5 = mt5
    return mt5


def reset():
    global _mt5
    _mt5 = None
