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

_info_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "clock_info.json")
if os.path.exists(_info_path):
    with open(_info_path) as _f:
        _info = json.load(_f)

    class _C(BaseManager):
        pass

    _C.register("clock_state")
    _c = _C(
        address=(_info["host"], _info["port"]),
        authkey=bytes.fromhex(_info["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
