"""High-resolution timer utilities for precise sleep on Windows.

Windows default timer resolution is ~15.6ms, making time.sleep() very
imprecise for real-time loops (e.g. 60fps needs 16.67ms per frame).

Calling timeBeginPeriod(1) increases system timer resolution to 1ms,
making time.sleep() accurate to ~1ms.  The calls are reference-counted
by Windows — each timeBeginPeriod must be paired with timeEndPeriod.
"""

import sys
from contextlib import contextmanager


@contextmanager
def high_resolution_timer():
    """Context manager that enables 1ms timer resolution on Windows.

    Usage::

        with high_resolution_timer():
            while running:
                ...
                time.sleep(remaining)  # now accurate to ~1ms
    """
    if sys.platform == "win32":
        import ctypes
        ctypes.windll.winmm.timeBeginPeriod(1)
    try:
        yield
    finally:
        if sys.platform == "win32":
            import ctypes
            ctypes.windll.winmm.timeEndPeriod(1)
