import os
import datetime as _dt_module
from multiprocessing.managers import BaseManager

_host = os.environ.get("CLOCK_MOCK_HOST")
if _host:
    _port = int(os.environ["CLOCK_MOCK_PORT"])
    _authkey = bytes.fromhex(os.environ["CLOCK_MOCK_AUTHKEY"])

    class _C(BaseManager):
        pass

    _C.register("clock_state")
    _c = _C(address=(_host, _port), authkey=_authkey)
    _c.connect()
    _proxy = _c.clock_state()

    _Orig = _dt_module.datetime

    class _FakeDatetime(_Orig):
        @classmethod
        def now(cls, tz=None):
            _mock = _proxy.get()
            if _mock:
                return _Orig.fromisoformat(_mock)
            return _Orig.now(tz)

    _dt_module.datetime = _FakeDatetime
