"""Python 版本兼容层"""

from __future__ import annotations

import asyncio
import sys

if sys.version_info >= (3, 11):
    asyncio_timeout = asyncio.timeout
else:
    import contextlib

    @contextlib.asynccontextmanager
    async def asyncio_timeout(delay: float):
        """asyncio.timeout 的 Python 3.10 兼容实现

        用 timed_out 标志区分超时取消和外部取消，
        避免将外部 task.cancel() 误判为 TimeoutError。
        """
        loop = asyncio.get_running_loop()
        task = asyncio.current_task()
        if task is None:
            raise RuntimeError("asyncio_timeout 必须在 Task 中使用")

        timed_out = False

        def _on_timeout():
            nonlocal timed_out
            timed_out = True
            task.cancel()

        handle = loop.call_later(delay, _on_timeout)
        try:
            yield
        except asyncio.CancelledError:
            if timed_out:
                raise TimeoutError(f"操作超时（{delay}s）")
            raise  # 外部取消，原样传播
        finally:
            handle.cancel()
