__mlib__ = "AbcBuiltins"

import typing
import functools

from myrrh.core.services.system import AbcRuntime

from . import mimportlib


class AbcBuiltins(AbcRuntime):
    import builtins as local_builtins

    __frameworkpath__ = "mpython.mbuiltins"

    __all__ = [
        "ArithmeticError",
        "AssertionError",
        "AttributeError",
        "BaseException",
        "BaseExceptionGroup",
        "BlockingIOError",
        "BrokenPipeError",
        "BufferError",
        "BytesWarning",
        "ChildProcessError",
        "ConnectionAbortedError",
        "ConnectionError",
        "ConnectionRefusedError",
        "ConnectionResetError",
        "DeprecationWarning",
        "EOFError",
        "Ellipsis",
        "EncodingWarning",
        "EnvironmentError",
        "Exception",
        "ExceptionGroup",
        "False",
        "FileExistsError",
        "FileNotFoundError",
        "FloatingPointError",
        "FutureWarning",
        "GeneratorExit",
        "IOError",
        "ImportError",
        "ImportWarning",
        "IndentationError",
        "IndexError",
        "InterruptedError",
        "IsADirectoryError",
        "KeyError",
        "KeyboardInterrupt",
        "LookupError",
        "MemoryError",
        "ModuleNotFoundError",
        "NameError",
        "None",
        "NotADirectoryError",
        "NotImplemented",
        "NotImplementedError",
        "OSError",
        "OverflowError",
        "PendingDeprecationWarning",
        "PermissionError",
        "ProcessLookupError",
        "RecursionError",
        "ReferenceError",
        "ResourceWarning",
        "RuntimeError",
        "RuntimeWarning",
        "StopAsyncIteration",
        "StopIteration",
        "SyntaxError",
        "SyntaxWarning",
        "SystemError",
        "SystemExit",
        "TabError",
        "TimeoutError",
        "True",
        "TypeError",
        "UnboundLocalError",
        "UnicodeDecodeError",
        "UnicodeEncodeError",
        "UnicodeError",
        "UnicodeTranslateError",
        "UnicodeWarning",
        "UserWarning",
        "ValueError",
        "Warning",
        "WindowsError",
        "ZeroDivisionError",
        "__import__",
        "abs",
        "aiter",
        "all",
        "anext",
        "any",
        "ascii",
        "bin",
        "bool",
        "breakpoint",
        "bytearray",
        "bytes",
        "callable",
        "chr",
        "classmethod",
        "compile",
        "complex",
        "copyright",
        "credits",
        "delattr",
        "dict",
        "dir",
        "divmod",
        "enumerate",
        "eval",
        "exec",
        "exit",
        "filter",
        "float",
        "format",
        "frozenset",
        "getattr",
        "globals",
        "hasattr",
        "hash",
        "help",
        "hex",
        "id",
        "input",
        "int",
        "isinstance",
        "issubclass",
        "iter",
        "len",
        "license",
        "list",
        "locals",
        "map",
        "max",
        "memoryview",
        "min",
        "next",
        "object",
        "oct",
        "open",
        "ord",
        "pow",
        "print",
        "property",
        "quit",
        "range",
        "repr",
        "reversed",
        "round",
        "set",
        "setattr",
        "slice",
        "sorted",
        "staticmethod",
        "str",
        "sum",
        "super",
        "tuple",
        "type",
        "vars",
        "zip",
    ]

    __doc__ = local_builtins.__doc__

    from builtins import (  # type: ignore[misc]
        ArithmeticError,
        AssertionError,
        AttributeError,
        BaseException,
        BaseExceptionGroup,
        BlockingIOError,
        BrokenPipeError,
        BufferError,
        BytesWarning,
        ChildProcessError,
        ConnectionAbortedError,
        ConnectionError,
        ConnectionRefusedError,
        ConnectionResetError,
        DeprecationWarning,
        EOFError,
        Ellipsis,
        EncodingWarning,
        EnvironmentError,
        Exception,
        ExceptionGroup,
        FileExistsError,
        FileNotFoundError,
        FloatingPointError,
        FutureWarning,
        GeneratorExit,
        IOError,
        ImportError,
        ImportWarning,
        IndentationError,
        IndexError,
        InterruptedError,
        IsADirectoryError,
        KeyError,
        KeyboardInterrupt,
        LookupError,
        MemoryError,
        ModuleNotFoundError,
        NameError,
        NotADirectoryError,
        NotImplemented,
        NotImplementedError,
        OSError,
        OverflowError,
        PendingDeprecationWarning,
        PermissionError,
        ProcessLookupError,
        RecursionError,
        ReferenceError,
        ResourceWarning,
        RuntimeError,
        RuntimeWarning,
        StopAsyncIteration,
        StopIteration,
        SyntaxError,
        SyntaxWarning,
        SystemError,
        SystemExit,
        TabError,
        TimeoutError,
        TypeError,
        UnboundLocalError,
        UnicodeDecodeError,
        UnicodeEncodeError,
        UnicodeError,
        UnicodeTranslateError,
        UnicodeWarning,
        UserWarning,
        ValueError,
        Warning,
        ZeroDivisionError,
        abs,
        aiter,
        all,
        anext,
        any,
        ascii,
        bin,
        bool,
        breakpoint,
        bytearray,
        bytes,
        callable,
        chr,
        compile,
        complex,
        copyright,
        credits,
        delattr,
        dict,
        dir,
        divmod,
        enumerate,
        eval,
        exec,
        exit,
        filter,
        float,
        format,
        frozenset,
        getattr,
        globals,
        hasattr,
        hash,
        help,
        hex,
        id,
        input,
        int,
        isinstance,
        issubclass,
        iter,
        len,
        license,
        list,
        locals,
        map,
        max,
        memoryview,
        min,
        next,
        object,
        oct,
        ord,
        pow,
        print,
        quit,
        range,
        repr,
        reversed,
        round,
        set,
        setattr,
        slice,
        sorted,
        str,
        sum,
        super,
        tuple,
        type,
        vars,
        zip,
    )

    __io = mimportlib.module_property("io")

    importlib = mimportlib.module_property(mimportlib)

    def __import__(self, name, globals=None, locals=None, fromlist=(), level=0):
        return self.importlib.__import__(name, globals, locals, fromlist, level)

    def open(
        self,
        file,
        mode="r",
        buffering=-1,
        encoding=None,
        errors=None,
        newline=None,
        closefd=True,
        opener=None,
    ):
        return self.__io.open(file, mode, buffering, encoding, errors, newline, closefd, opener)

    __def_builtins__: dict[str, typing.Any] = dict(__builtins__)  # type: ignore[arg-type]

    @functools.cached_property
    def __builtins__(self):
        __builtins__ = dict(self.__def_builtins__)
        __builtins__["open"] = self.open
        __builtins__["__import__"] = self.__import__

        return __builtins__


def wrap_module(module, runtimeModule, wrapped={}):
    import importlib.util

    builtins = AbcBuiltins(runtimeModule)

    def __import__(name, globals=None, locals=None, fromlist=(), level=0):
        mod = wrapped.get(name)
        if mod is None:
            mod = builtins.__import__(name, globals, locals, fromlist, level)
        return mod

    __builtins__ = dict(module.__builtins__)
    __builtins__.update(builtins.__builtins__)
    __builtins__["__import__"] = __import__

    mod = importlib.util.module_from_spec(module.__spec__)

    assert mod is not module

    mod.__builtins__ = __builtins__
    mod.__loader__.exec_module(mod)

    return mod
