"""
Runtime hook: patch asyncio/__init__.py in frozen sys._MEIPASS.

Problem: asyncio/__init__.py uses 'from .base_events import *' which imports
base_events' names into the local namespace but does NOT bind the 'base_events'
module name itself. The '__all__ = (base_events.__all__ + ...)' line fails with
NameError because 'base_events' is not a defined name.

Fix: inject 'from . import base_events' (relative import) BEFORE __all__
is evaluated, so the name 'base_events' is bound in the asyncio package namespace.
This runs BEFORE any user code at the earliest possible moment in frozen startup.
"""
import sys, os
from pathlib import Path

if getattr(sys, 'frozen', False):
    _meipass = Path(sys._MEIPASS)
    _asyncio_init = _meipass / 'asyncio' / '__init__.py'
    if _asyncio_init.exists():
        try:
            content = _asyncio_init.read_text(encoding='utf-8')
        except Exception:
            content = ''
        # Only patch if not already patched
        if 'from . import base_events  # frozen-fix: bind' not in content:
            lines = content.split('\n')
            new_lines = []
            for line in lines:
                new_lines.append(line)
                # After 'from .transports import *', inject the relative import
                # so that 'base_events' name is bound in the asyncio namespace
                if line.startswith('from .transports import') or line == 'from .transports import *':
                    new_lines.append('')
                    new_lines.append(
                        'from . import base_events, coroutines, events, exceptions, futures, locks, protocols, runners, queues, streams, subprocess, tasks, taskgroups, timeouts, threads, transports  # frozen-fix: bind all submodule names'
                    )
            patched = '\n'.join(new_lines)
            try:
                _asyncio_init.write_text(patched, encoding='utf-8')
            except Exception:
                pass  # read-only filesystem