import base64
import json
import re
import struct
import time
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Sequence, cast

import requests
from wasmer.wasmer import (
    Function,
    FunctionType,
    Instance,
    Module,
    Store,
    Type,
    engine,
)
from wasmer_compiler_cranelift.wasmer_compiler_cranelift import Compiler

from consumet_mc.extractors.megacloud.megacloud_decodedpng import decoded_png
from consumet_mc.utils import crypto

# pyright: reportUnusedParameter=false

wasm: Any
arr: List = [None] * 128
date_now: float = int(time.time() * 1000)
referer: str = ""
user_agent: str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
store = Store(engine.Universal(Compiler))
data_view = None
memory_buff = None
size = 0


data_url = "data:image/png;base64, "


class Undefined:
    pass


class F64:
    pass


@dataclass
class Meta:
    content: str


@dataclass
class ImageData:
    height: int
    width: int
    data: Any


@dataclass
class Image:
    src: str
    height: int
    width: int
    complete: bool


@dataclass
class NodeList:
    image: Image
    context2d: None
    length: int

    def __len__(self):
        return len(self.__dataclass_fields__)


class FakeStorage:
    def __init__(self) -> None:
        self._data: Dict[str, Any] = {}

    def setItem(self, key: str, value: Any):
        self._data[key] = value

    def getItem(self, key: str, default_return: Optional[Any] = None):
        return self._data.get(key, default_return)


@dataclass
class Navigator:
    webdriver: bool
    userAgent: str


@dataclass
class Performance:
    time_origin: float


@dataclass
class Document:
    cookie: str


@dataclass
class Location:
    href: str
    origin: str


class FakeWindow:
    def __init__(self) -> None:
        self.localStorage: FakeStorage = FakeStorage()
        self.error: bool = False
        self.navigator: Navigator = Navigator(False, user_agent)
        self.length: int = 0
        self.document: Document = Document("")
        self.origin: str = ""
        self.location: Location = Location("", "")
        self.performance: Performance = Performance(float(date_now))
        self.xrax: str = ""
        self.c: bool = False
        self.G: str = ""
        self.crypto = crypto
        self.msCrypto = crypto
        self.browser_version = 1878522368

    def z(self, a: Any):
        return [(4278190080 & a) >> 24, (16711680 & a) >> 16, (65280 & a) >> 8, 255 & a]


@dataclass
class Canvas:
    base_url: str
    width: int
    height: int
    style: Dict
    context2d: Any


undefined = Undefined()
arr.extend([Undefined, None, True, False])
pointer = len(arr)
image_data = ImageData(50, 65, decoded_png)
meta = Meta("")
fake_window = FakeWindow()
canvas = Canvas("", 0, 0, {"style": {"display": "inline"}}, None)
node_list = NodeList(Image("", 50, 65, True), None, 1)


def get_meta(url: str):
    headers = {"userAgent": user_agent, "Referrer": referer}
    resp = requests.get(url, headers=headers)
    txt = resp.text
    regx = r'name="j_crt" content="[A-Za-z0-9]*"'
    regx = r"name=\"j_crt\" content=\"[A-Za-z0-9]*"
    match = re.search(regx, txt)
    content: str = ""
    if match:
        content = match.group(0)[match.group(0).rindex('"') + 1 :]
    meta.content = content + "=="


def get(index: int):
    return arr[index]


def shift(QP: int):
    if QP >= 132:
        global pointer
        arr[QP] = pointer
        pointer = QP


def shift_get(QP: int):
    Qn = get(QP)
    shift(QP)
    return Qn


def add_to_stack(item: Any):
    global pointer
    if pointer == len(arr):
        arr.append(len(arr) + 1)
    Qn = pointer
    pointer = arr[Qn]
    arr[Qn] = item
    return Qn


def args(QP, Qn, QT, func):
    Qx = {
        "a": QP,
        "b": Qn,
        "cnt": 1,
        "dtor": QT,
    }

    def wrapper(*Qw):
        Qx["cnt"] += 1
        try:
            return func(Qx["a"], Qx["b"], *Qw)
        finally:
            Qx["cnt"] -= 1
            if Qx["cnt"] == 0:
                wasm.__wbindgen_export_2.get(Qx["dtor"])(Qx["a"], Qx["b"])
                Qx["a"] = 0

    return wrapper


def export3(QP: Any, Qn: Any):
    return shift_get(wasm.__wbindgen_export_3(QP, Qn))


def export4(Qy: Any, QO: Any, QX: Any):
    index = add_to_stack(QX)
    wasm.__wbindgen_export_4(Qy, QO, index)


def export5(QP: Any, Qn: Any):
    wasm.__wbindgen_export_5(QP, Qn)


def is_none(test: Any):
    return test is None


def is_detached(buf):
    try:
        _ = len(buf)
        return False
    except ValueError:
        return True


def get_data_view():
    global data_view

    if data_view is None or is_detached(data_view):
        data_view = memoryview(wasm.memory.buffer)
    return data_view


def write_int32_le(buf: memoryview, offset: int, value: int):
    struct.pack_into("<i", buf, offset, value)


def write_float64_le(buf: memoryview, offset: int, value: int):
    struct.pack_into("<d", buf, offset, value)


def read_int32_le(buf: memoryview, offset: int):
    return struct.unpack_from("<i", buf, offset)[0]


def decode_sub(index: int, offset: int):
    index &= 0xFFFFFFFF
    mem = get_mem_buff()
    slice_ = bytearray(mem[index : index + offset])
    slice_decoded = slice_.decode("utf-8")
    return slice_decoded


def apply_to_window(func: Callable[..., int], *args) -> int:
    try:
        return func(*args)
    except Exception as e:
        wasm.__wbindgen_export_6(add_to_stack(e))
        return -1


def encode(text: str, array: memoryview) -> dict:
    encoded = text.encode("utf-8")
    written = len(encoded)
    array[:written] = encoded
    return {"read": len(text), "written": written}


def get_mem_buff():
    global memory_buff
    if memory_buff is not None and len(memory_buff) > 0:
        return memory_buff

    memory_buff = wasm.memory.uint8_view()
    return memory_buff


def Qj(QP: Sequence[int], Qn: Any):
    global size
    Qn = Qn(len(QP), 1) & 0xFFFFFFFF
    _buffer = get_mem_buff()
    _buffer[Qn : Qn + len(QP)] = QP

    size = len(QP)
    return Qn


def parse(text: str, func, func2=None):
    global size
    buffer = get_mem_buff()

    if func2 is None:
        encoded = text.encode("utf-8")
        parsed_index = func(len(encoded), 1)
        parsed_index &= 0xFFFFFFFF
        buffer[parsed_index : parsed_index + len(encoded)] = encoded
        size = len(encoded)
        return parsed_index

    len_text = len(text)
    parsed_len = func(len_text, 1)
    parsed_len &= 0xFFFFFFFF

    i = 0
    for i in range(len_text):
        char = ord(text[i])
        if 127 < char:
            break
        buffer[parsed_len + i] = char

    i += 1
    if i != len_text:
        if i != 0:
            text = text[i:]
        len_text_mod = i + (3 * len(text))
        parsed_len = func2(parsed_len, len_text, len_text_mod, 1)
        len_text = len_text_mod
        parsed_len &= 0xFFFFFFFF

        encoded_buf = get_mem_buff()[parsed_len + i : parsed_len + len_text]
        # encode() writes to buffer and returns number of bytes written
        result = encode(text, encoded_buf)
        i += result["written"]

        parsed_len = func2(parsed_len, len_text, i, 1)
        parsed_len &= 0xFFFFFFFF

    size = i
    return parsed_len


def init_wasm():
    def __wbindgen_is_function(index: int) -> int:
        raise NotImplementedError("__wbindgen_is_function not implemented")

    def __wbindgen_is_string(index: int) -> int:
        raise NotImplementedError("__wbindgen_is_string not implemented")

    def __wbindgen_is_object(index: int) -> int:
        obj = get(index)
        is_object = isinstance(obj, object) and obj is not None
        return is_object

    def __wbindgen_number_get(offset: int, index: int):
        number = get(index)
        _view = get_data_view()
        write_float64_le(_view, offset + 8, 0 if number is None else number)
        write_int32_le(_view, offset, 0 if number is None else 1)

    def __wbindgen_string_get(offset: int, index: int):
        # todo
        str = get(index)
        val = parse(str, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1)
        _view = get_data_view()
        write_int32_le(_view, offset + 4, size)
        write_int32_le(_view, offset, val)

    def __wbindgen_object_drop_ref(index: int):
        shift_get(index)

    def __wbindgen_cb_drop(index: int) -> int:
        raise NotImplementedError("__wbindgen_cb_drop not implemented")

    def __wbindgen_string_new(index: int, offset: int) -> int:
        return add_to_stack(decode_sub(index, offset))

    def __wbindgen_is_null(index: int):
        return get(index) is None

    def __wbindgen_is_undefined(index: int) -> bool:
        return get(index) == undefined

    def __wbindgen_boolean_get(index: int) -> int:
        _boolean = get(index)
        if type(_boolean) is bool:
            if _boolean:
                return 1
            else:
                return 0
        else:
            return 2

    def __wbg_instanceof_CanvasRenderingContext2d_4ec30ddd3f29f8f9(val: int) -> int:
        return True

    def __wbg_subarray_adc418253d76e2f1(index: int, num1: int, num2: int) -> int:
        num1 = num1 & 0xFFFFFFFF
        num2 = num2 & 0xFFFFFFFF
        return add_to_stack(memoryview(get(index))[num1:num2])

    def __wbg_randomFillSync_5c9c955aa56b6049(val: int, val2: int):
        raise NotImplementedError(
            "__wbg_randomFillSync_5c9c955aa56b6049 not implemented"
        )

    def __wbg_getRandomValues_3aa56aa6edec874c(index: int, index2: int):
        return apply_to_window(get(index).get_random_values, get(index2))

    def __wbg_msCrypto_eb05e62b530a1508(index: int) -> int:
        raise NotImplementedError("__wbg_msCrypto_eb05e62b530a1508 not implemented")

    def __wbg_toString_6eb7c1f755c00453(index: int) -> int:
        fakestr = "[object Storage]"
        return add_to_stack(fakestr)

    def __wbg_toString_139023ab33acec36(index: int) -> int:
        return add_to_stack(str(get(index)))

    def __wbg_require_cca90b1a94a0255b() -> int:
        raise NotImplementedError("__wbg_require_cca90b1a94a0255b not implemented")

    def __wbg_crypto_1d1f22824a6a080c(index: int) -> int:
        return add_to_stack(get(index).crypto)

    def __wbg_process_4a72847cc503995b(index: int) -> int:
        return add_to_stack(get(index).process)

    def __wbg_versions_f686565e586dd935(index: int) -> int:
        raise NotImplementedError("__wbg_versions_f686565e586dd935 not implemented")

    def __wbg_node_104a2ff8d6ea03a2(index: int) -> int:
        raise NotImplementedError("__wbg_node_104a2ff8d6ea03a2 not implemented")

    def __wbg_localStorage_3d538af21ea07fcc(index: int) -> int:
        def _f(index):
            data = fake_window.localStorage
            return 0 if is_none(data) else add_to_stack(data)

        return apply_to_window(_f, index)

    def __wbg_setfillStyle_59f426135f52910f(val: int, val2: int):
        pass

    def __wbg_setshadowBlur_229c56539d02f401(val: int, val2: "F64"):  # type: ignore[name-defined] # noqa: F821
        pass

    def __wbg_setshadowColor_340d5290cdc4ae9d(val: int, val2: int, val3: int):
        pass

    def __wbg_setfont_16d6e31e06a420a5(val: int, val2: int, val3: int):
        pass

    def __wbg_settextBaseline_c3266d3bd4a6695c(val: int, val2: int, val3: int):
        pass

    def __wbg_drawImage_cb13768a1bdc04bd(val: int, val2: int, val3: "F64", val4: "F64"):  # type: ignore[name-defined] # noqa: F821
        pass

    def __wbg_getImageData_66269d289f37d3c7(
        val: int,
        val2: "F64",  # type: ignore[name-defined] # noqa: F821
        val3: "F64",  # type: ignore[name-defined] # noqa: F821
        val4: "F64",  # type: ignore[name-defined] # noqa: F821
        val5: "F64",  # type: ignore[name-defined] # noqa: F821
    ) -> int:
        return add_to_stack(image_data)

    def __wbg_rect_2fa1df87ef638738(
        val: int,
        val2: "F64",
        val3: "F64",
        val4: "F64",
        val5: "F64",
    ):
        pass

    def __wbg_fillRect_4dd28e628381d240(
        val: int, val2: "F64", val3: "F64", val4: "F64", val5: "F64"
    ):
        pass

    def __wbg_fillText_07e5da9e41652f20(
        val: int, val2: int, val3: int, val4: "F64", val5: "F64"
    ):
        pass

    def __wbg_setProperty_5144ddce66bbde41(
        val: int, val2: int, val3: int, val4: int, val5: int
    ):
        return 0

    def __wbg_createElement_03cf347ddad1c8c0(
        index: int, decodeIndex: int, decodeIndexOffset: int
    ) -> int:
        return apply_to_window(lambda: add_to_stack(canvas))

    def __wbg_querySelector_118a0639aa1f51cd(
        index: int, decodeIndex: int, decodeOffset: int
    ) -> int:
        return apply_to_window(lambda: add_to_stack(meta))

    def __wbg_querySelectorAll_50c79cd4f7573825(val: int, val2: int, val3: int) -> int:
        return apply_to_window(lambda: add_to_stack(node_list))

    def __wbg_getAttribute_706ae88bd37410fa(
        offset: int, index: int, decodeIndex: int, decodeOffset: int
    ):
        attr = meta.content
        todo = (
            0
            if is_none(attr)
            else parse(attr, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1)
        )
        _view = get_data_view()
        write_int32_le(_view, offset + 4, size)
        write_int32_le(_view, offset, todo)

    def __wbg_target_6795373f170fd786(index: int) -> int:
        raise NotImplementedError("__wbg_target_6795373f170fd786 not implemented")

    def __wbg_addEventListener_f984e99465a6a7f4(
        val: int, val2: int, val3: int, val4: int
    ):
        raise NotImplementedError(
            "__wbg_addEventListener_f984e99465a6a7f4 not implemented"
        )

    def __wbg_instanceof_HtmlCanvasElement_1e81f71f630e46bc(index: int) -> int:
        return True

    def __wbg_setwidth_233645b297bb3318(index: int, set: int):
        get(index).width = set & 0xFFFFFFFF

    def __wbg_setheight_fcb491cf54e3527c(index: int, set: int):
        get(index).height = set & 0xFFFFFFFF

    def __wbg_getContext_dfc91ab0837db1d1(index: int, val1: int, val2: int) -> int:
        def _f(x):
            return add_to_stack(get(x).context2d)

        return apply_to_window(_f, index)

    def __wbg_toDataURL_97b108dd1a4b7454(offset: int, index: int):
        def _f(offset, index):
            _data_url = parse(
                data_url, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1
            )
            _view = get_data_view()
            write_int32_le(_view, offset + 4, size)
            write_int32_le(_view, offset, _data_url)
            return 0

        return apply_to_window(_f, offset, index)

    def __wbg_instanceof_HtmlDocument_1100f8a983ca79f9():
        raise NotImplementedError(
            "__wbg_instanceof_HtmlDocument_1100f8a983ca79f9 not implemented"
        )

    def __wbg_style_ca229e3326b3c3fb(index: int) -> int:
        add_to_stack(get(index).style)
        return 0

    def __wbg_instanceof_HtmlImageElement_9c82d4e3651a8533(index: int) -> int:
        return True

    def __wbg_src_87a0e38af6229364(offset: int, index: int):
        _src = parse(get(index).src, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1)
        _view = get_data_view()
        write_int32_le(_view, offset + 4, size)
        write_int32_le(_view, offset, _src)

    def __wbg_width_e1a38bdd483e1283(index: int) -> int:
        return get(index).width

    def __wbg_height_e4cc2294187313c9(index: int) -> int:
        return get(index).height

    def __wbg_complete_1162c2697406af11(index: int) -> int:
        return get(index).complete

    def __wbg_data_d34dc554f90b8652(offset: int, index: int):
        _data = Qj(get(index).data, wasm.__wbindgen_export_0)
        _view = get_data_view()
        write_int32_le(_view, offset + 4, size)
        write_int32_le(_view, offset, _data)

    def __wbg_origin_305402044aa148ce(index: int, val2: int):
        def _f(offset, index):
            _origin = parse(
                get(index).origin, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1
            )
            _view = get_data_view()
            write_int32_le(_view, offset + 4, size)
            write_int32_le(_view, offset, _origin)
            return 0

        return apply_to_window(_f, index, val2)

    def __wbg_length_8a9352f7b7360c37(index: int) -> int:
        return get(index).length

    def __wbg_get_c30ae0782d86747f(index: int, offset: int) -> int:
        _image = get(index).image
        if _image is None:
            return 0
        return add_to_stack(_image)

    def __wbg_timeOrigin_f462952854d802ec(index: int) -> "F64":
        return get(index).time_origin

    def __wbg_instanceof_Window_cee7a886d55e7df5(val: int) -> int:
        return 1

    def __wbg_document_eb7fd66bde3ee213(index: int) -> int:
        doc = get(index).document
        if doc is None:
            return 0
        return add_to_stack(doc)

    def __wbg_location_b17760ac7977a47a(index: int) -> int:
        return add_to_stack(get(index).location)

    def __wbg_performance_4ca1873776fdb3d2(index: int) -> int:
        _performance = get(index).performance
        return 0 if is_none(_performance) else add_to_stack(_performance)

    def __wbg_origin_e1f8acdeb3a39a2b(offset: int, index: int):
        _origin = parse(
            get(index).origin, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1
        )
        _view = get_data_view()
        write_int32_le(_view, offset + 4, size)
        write_int32_le(_view, offset, _origin)

    def __wbg_get_8986951b1ee310e0(index: int, decode1: int, decode2: int) -> int:
        data = getattr(get(index), decode_sub(decode1, decode2), undefined)
        return 0 if is_none(data) else add_to_stack(data)

    def __wbg_setTimeout_6ed7182ebad5d297(val: int, val2: int, val3: int) -> int:
        return apply_to_window(lambda: 7)

    def __wbg_self_05040bd9523805b9() -> int:
        return apply_to_window(lambda: add_to_stack(fake_window))

    def __wbg_window_adc720039f2cb14f() -> int:
        raise NotImplementedError("__wbg_window_adc720039f2cb14f not implemented")

    def __wbg_globalThis_622105db80c1457d() -> int:
        raise NotImplementedError("__wbg_globalThis_622105db80c1457d not implemented")

    def __wbg_global_f56b013ed9bcf359() -> int:
        raise NotImplementedError("__wbg_global_f56b013ed9bcf359 not implemented")

    def __wbg_newnoargs_cfecb3965268594c(index: int, offset: int) -> int:
        raise NotImplementedError("__wbg_newnoargs_cfecb3965268594c not implemented")

    def __wbindgen_object_clone_ref(index: int) -> int:
        return add_to_stack(get(index))

    def __wbg_eval_c824e170787ad184(index: int, offset: int) -> int:
        def _f(index, offset):
            fake_str = "fake_" + decode_sub(index, offset)
            ev = None
            try:
                try:
                    ev = eval(fake_str)
                except AttributeError:
                    ev = undefined
            except SyntaxError:
                ev = exec(fake_str)

            return add_to_stack(ev)

        return apply_to_window(_f, index, offset)

    def __wbg_call_3f093dd26d5569f8(index: int, index2: int) -> int:
        raise NotImplementedError("__wbg_call_3f093dd26d5569f8 not implemented")

    def __wbg_call_67f2111acd2dfdb6(index: int, index2: int, index3: int) -> int:
        raise NotImplementedError("__wbg_call_67f2111acd2dfdb6 not implemented")

    def __wbg_set_961700853a212a39(index: int, index2: int, index3: int) -> int:
        def _f(index, index2, index3):
            obj = get(index)
            key = get(index2)
            value = get(index3)
            setattr(obj, key, value)
            return 0

        return apply_to_window(_f, index, index2, index3)

    def __wbg_buffer_b914fb8b50ebbc3e(index: int) -> int:
        return add_to_stack(memoryview(get(index).buffer))

    def __wbg_newwithbyteoffsetandlength_0de9ee56e9f6ee6e(
        index: int, val: int, val2: int
    ) -> int:
        val = val & 0xFFFFFFFF
        val2 = val2 & 0xFFFFFFFF
        return add_to_stack(memoryview(get(index))[val : val + val2].tobytes())

    def __wbg_newwithlength_0d03cef43b68a530(length: int) -> int:
        return add_to_stack(bytearray(int(length) & 0xFFFFFFFF))

    def __wbg_new_b1f2d6842d615181(index: int) -> int:
        return add_to_stack(memoryview(get(index)))

    def __wbg_buffer_67e624f5a0ab2319(index: int) -> int:
        return add_to_stack(get(index).obj)

    def __wbg_length_21c4b0ae73cba59d(index: int) -> int:
        return len(get(index))

    def __wbg_set_7d988c98e6ced92d(index: int, index2: int, val: int):
        val = val & 0xFFFFFFFF
        get(index)[val : val + len(get(index2))] = get(index2)

    def __wbindgen_debug_string():
        raise NotImplementedError("__wbindgen_debug_string not implemented")

    def __wbindgen_throw(index: int, offset: int):
        raise NotImplementedError("__wbindgen_throw not implemented")

    def __wbindgen_memory() -> int:
        return add_to_stack(wasm.memory)

    def __wbindgen_closure_wrapper117(Qn: int, QT: int, QV: int) -> int:
        return add_to_stack(args(Qn, QT, 2, export3))

    def __wbindgen_closure_wrapper119(Qn: int, QT: int, QV: int) -> int:
        return add_to_stack(args(Qn, QT, 2, export4))

    def __wbindgen_closure_wrapper121(Qn: int, QT: int, QV: int) -> int:
        return add_to_stack(args(Qn, QT, 2, export5))

    def __wbindgen_closure_wrapper123(Qn: int, QT: int, QV: int) -> int:
        return add_to_stack(args(Qn, QT, 9, export4))

    wasm_obj = {
        "wbg": {
            "__wbindgen_is_function": Function(store, __wbindgen_is_function),
            "__wbindgen_is_string": Function(store, __wbindgen_is_string),
            "__wbindgen_is_object": Function(store, __wbindgen_is_object),
            "__wbindgen_number_get": Function(store, __wbindgen_number_get),
            "__wbindgen_string_get": Function(store, __wbindgen_string_get),
            "__wbindgen_object_drop_ref": Function(store, __wbindgen_object_drop_ref),
            "__wbindgen_cb_drop": Function(store, __wbindgen_cb_drop),
            "__wbindgen_string_new": Function(store, __wbindgen_string_new),
            "__wbindgen_is_null": Function(
                store, __wbindgen_is_null, FunctionType([Type.I32], [Type.I32])
            ),
            "__wbindgen_is_undefined": Function(
                store, __wbindgen_is_undefined, FunctionType([Type.I32], [Type.I32])
            ),
            "__wbindgen_boolean_get": Function(store, __wbindgen_boolean_get),
            "__wbg_instanceof_CanvasRenderingContext2d_4ec30ddd3f29f8f9": Function(
                store, __wbg_instanceof_CanvasRenderingContext2d_4ec30ddd3f29f8f9
            ),
            "__wbg_subarray_adc418253d76e2f1": Function(
                store, __wbg_subarray_adc418253d76e2f1
            ),
            "__wbg_randomFillSync_5c9c955aa56b6049": Function(
                store, __wbg_randomFillSync_5c9c955aa56b6049
            ),
            "__wbg_getRandomValues_3aa56aa6edec874c": Function(
                store, __wbg_getRandomValues_3aa56aa6edec874c
            ),
            "__wbg_msCrypto_eb05e62b530a1508": Function(
                store, __wbg_msCrypto_eb05e62b530a1508
            ),
            "__wbg_toString_6eb7c1f755c00453": Function(
                store, __wbg_toString_6eb7c1f755c00453
            ),
            "__wbg_toString_139023ab33acec36": Function(
                store, __wbg_toString_139023ab33acec36
            ),
            "__wbg_require_cca90b1a94a0255b": Function(
                store, __wbg_require_cca90b1a94a0255b
            ),
            "__wbg_crypto_1d1f22824a6a080c": Function(
                store, __wbg_crypto_1d1f22824a6a080c
            ),
            "__wbg_process_4a72847cc503995b": Function(
                store, __wbg_process_4a72847cc503995b
            ),
            "__wbg_versions_f686565e586dd935": Function(
                store, __wbg_versions_f686565e586dd935
            ),
            "__wbg_node_104a2ff8d6ea03a2": Function(store, __wbg_node_104a2ff8d6ea03a2),
            "__wbg_localStorage_3d538af21ea07fcc": Function(
                store, __wbg_localStorage_3d538af21ea07fcc
            ),
            "__wbg_setfillStyle_59f426135f52910f": Function(
                store, __wbg_setfillStyle_59f426135f52910f
            ),
            "__wbg_setshadowBlur_229c56539d02f401": Function(
                store, __wbg_setshadowBlur_229c56539d02f401
            ),
            "__wbg_setshadowColor_340d5290cdc4ae9d": Function(
                store, __wbg_setshadowColor_340d5290cdc4ae9d
            ),
            "__wbg_setfont_16d6e31e06a420a5": Function(
                store, __wbg_setfont_16d6e31e06a420a5
            ),
            "__wbg_settextBaseline_c3266d3bd4a6695c": Function(
                store, __wbg_settextBaseline_c3266d3bd4a6695c
            ),
            "__wbg_drawImage_cb13768a1bdc04bd": Function(
                store, __wbg_drawImage_cb13768a1bdc04bd
            ),
            "__wbg_getImageData_66269d289f37d3c7": Function(
                store, __wbg_getImageData_66269d289f37d3c7
            ),
            "__wbg_rect_2fa1df87ef638738": Function(store, __wbg_rect_2fa1df87ef638738),
            "__wbg_fillRect_4dd28e628381d240": Function(
                store, __wbg_fillRect_4dd28e628381d240
            ),
            "__wbg_fillText_07e5da9e41652f20": Function(
                store, __wbg_fillText_07e5da9e41652f20
            ),
            "__wbg_setProperty_5144ddce66bbde41": Function(
                store, __wbg_setProperty_5144ddce66bbde41
            ),
            "__wbg_createElement_03cf347ddad1c8c0": Function(
                store, __wbg_createElement_03cf347ddad1c8c0
            ),
            "__wbg_querySelector_118a0639aa1f51cd": Function(
                store, __wbg_querySelector_118a0639aa1f51cd
            ),
            "__wbg_querySelectorAll_50c79cd4f7573825": Function(
                store, __wbg_querySelectorAll_50c79cd4f7573825
            ),
            "__wbg_getAttribute_706ae88bd37410fa": Function(
                store, __wbg_getAttribute_706ae88bd37410fa
            ),
            "__wbg_target_6795373f170fd786": Function(
                store, __wbg_target_6795373f170fd786
            ),
            "__wbg_addEventListener_f984e99465a6a7f4": Function(
                store, __wbg_addEventListener_f984e99465a6a7f4
            ),
            "__wbg_instanceof_HtmlCanvasElement_1e81f71f630e46bc": Function(
                store, __wbg_instanceof_HtmlCanvasElement_1e81f71f630e46bc
            ),
            "__wbg_setwidth_233645b297bb3318": Function(
                store, __wbg_setwidth_233645b297bb3318
            ),
            "__wbg_setheight_fcb491cf54e3527c": Function(
                store, __wbg_setheight_fcb491cf54e3527c
            ),
            "__wbg_getContext_dfc91ab0837db1d1": Function(
                store, __wbg_getContext_dfc91ab0837db1d1
            ),
            "__wbg_toDataURL_97b108dd1a4b7454": Function(
                store, __wbg_toDataURL_97b108dd1a4b7454
            ),
            "__wbg_instanceof_HtmlDocument_1100f8a983ca79f9": Function(
                store, __wbg_instanceof_HtmlDocument_1100f8a983ca79f9
            ),
            "__wbg_style_ca229e3326b3c3fb": Function(
                store, __wbg_style_ca229e3326b3c3fb
            ),
            "__wbg_instanceof_HtmlImageElement_9c82d4e3651a8533": Function(
                store, __wbg_instanceof_HtmlImageElement_9c82d4e3651a8533
            ),
            "__wbg_src_87a0e38af6229364": Function(store, __wbg_src_87a0e38af6229364),
            "__wbg_width_e1a38bdd483e1283": Function(
                store, __wbg_width_e1a38bdd483e1283
            ),
            "__wbg_height_e4cc2294187313c9": Function(
                store, __wbg_height_e4cc2294187313c9
            ),
            "__wbg_complete_1162c2697406af11": Function(
                store, __wbg_complete_1162c2697406af11
            ),
            "__wbg_data_d34dc554f90b8652": Function(store, __wbg_data_d34dc554f90b8652),
            "__wbg_origin_305402044aa148ce": Function(
                store, __wbg_origin_305402044aa148ce
            ),
            "__wbg_length_8a9352f7b7360c37": Function(
                store, __wbg_length_8a9352f7b7360c37
            ),
            "__wbg_get_c30ae0782d86747f": Function(store, __wbg_get_c30ae0782d86747f),
            "__wbg_timeOrigin_f462952854d802ec": Function(
                store, __wbg_timeOrigin_f462952854d802ec
            ),
            "__wbg_instanceof_Window_cee7a886d55e7df5": Function(
                store, __wbg_instanceof_Window_cee7a886d55e7df5
            ),
            "__wbg_document_eb7fd66bde3ee213": Function(
                store, __wbg_document_eb7fd66bde3ee213
            ),
            "__wbg_location_b17760ac7977a47a": Function(
                store, __wbg_location_b17760ac7977a47a
            ),
            "__wbg_performance_4ca1873776fdb3d2": Function(
                store, __wbg_performance_4ca1873776fdb3d2
            ),
            "__wbg_origin_e1f8acdeb3a39a2b": Function(
                store, __wbg_origin_e1f8acdeb3a39a2b
            ),
            "__wbg_get_8986951b1ee310e0": Function(store, __wbg_get_8986951b1ee310e0),
            "__wbg_setTimeout_6ed7182ebad5d297": Function(
                store, __wbg_setTimeout_6ed7182ebad5d297
            ),
            "__wbg_self_05040bd9523805b9": Function(store, __wbg_self_05040bd9523805b9),
            "__wbg_window_adc720039f2cb14f": Function(
                store, __wbg_window_adc720039f2cb14f
            ),
            "__wbg_globalThis_622105db80c1457d": Function(
                store, __wbg_globalThis_622105db80c1457d
            ),
            "__wbg_global_f56b013ed9bcf359": Function(
                store, __wbg_global_f56b013ed9bcf359
            ),
            "__wbg_newnoargs_cfecb3965268594c": Function(
                store, __wbg_newnoargs_cfecb3965268594c
            ),
            "__wbindgen_object_clone_ref": Function(store, __wbindgen_object_clone_ref),
            "__wbg_eval_c824e170787ad184": Function(store, __wbg_eval_c824e170787ad184),
            "__wbg_call_3f093dd26d5569f8": Function(store, __wbg_call_3f093dd26d5569f8),
            "__wbg_call_67f2111acd2dfdb6": Function(store, __wbg_call_67f2111acd2dfdb6),
            "__wbg_set_961700853a212a39": Function(store, __wbg_set_961700853a212a39),
            "__wbg_buffer_b914fb8b50ebbc3e": Function(
                store, __wbg_buffer_b914fb8b50ebbc3e
            ),
            "__wbg_newwithbyteoffsetandlength_0de9ee56e9f6ee6e": Function(
                store, __wbg_newwithbyteoffsetandlength_0de9ee56e9f6ee6e
            ),
            "__wbg_newwithlength_0d03cef43b68a530": Function(
                store, __wbg_newwithlength_0d03cef43b68a530
            ),
            "__wbg_new_b1f2d6842d615181": Function(store, __wbg_new_b1f2d6842d615181),
            "__wbg_buffer_67e624f5a0ab2319": Function(
                store, __wbg_buffer_67e624f5a0ab2319
            ),
            "__wbg_length_21c4b0ae73cba59d": Function(
                store, __wbg_length_21c4b0ae73cba59d
            ),
            "__wbg_set_7d988c98e6ced92d": Function(store, __wbg_set_7d988c98e6ced92d),
            "__wbindgen_debug_string": Function(store, __wbindgen_debug_string),
            "__wbindgen_throw": Function(store, __wbindgen_throw),
            "__wbindgen_memory": Function(store, __wbindgen_memory),
            "__wbindgen_closure_wrapper117": Function(
                store, __wbindgen_closure_wrapper117
            ),
            "__wbindgen_closure_wrapper119": Function(
                store, __wbindgen_closure_wrapper119
            ),
            "__wbindgen_closure_wrapper121": Function(
                store, __wbindgen_closure_wrapper121
            ),
            "__wbindgen_closure_wrapper123": Function(
                store, __wbindgen_closure_wrapper123
            ),
        }
    }

    return wasm_obj


def QN(QP, Qn):
    QT = None
    Qt = None

    if isinstance(QP, requests.Response):
        QT = QP.raw.data
        module = Module(store, QT)
        Qt = Instance(module, Qn)
        return {"bytes": QT, "instance": Qt, "module": module}
    else:
        if isinstance(QP, Module):
            Qt = Instance(QP, Qn)
            return {
                "instance": Qt,
                "module": QP,
            }
        else:
            module = Module(store, QP)
            Qt = Instance(module, Qn)
            return {"bytes": QP, "instance": Qt, "module": module}


def assign_wasm(instance):
    global wasm
    global data_view
    global memory_buff
    wasm = instance.exports
    data_view = None
    memory_buff = None


def QZ(QP):
    global wasm

    if wasm is not None:
        return wasm
    else:
        Qn = init_wasm()

        if not isinstance(QP, Module):
            QP = Module(store, QP)

        instance = Instance(QP, Qn)
        wasm = assign_wasm(instance)
        return wasm


def load_wasm(url: Any):
    mod = init_wasm()

    response = requests.get(url, stream=True)
    response.raise_for_status()
    result = QN(response, mod)

    instance = result.get("instance", url)
    buffer = result.get("bytes")

    assign_wasm(instance)

    return buffer


def groot():
    global wasm
    wasm.groot()


def init(QP: Any):
    QZ(QP)


wasm_loader = {"load_wasm": load_wasm, "groot": groot, "init": init}


def V(url: str):
    try:
        Q0 = wasm_loader["load_wasm"](url)
        wasm_loader["groot"]()
        jwt_plugin = getattr(fake_window, "jwt_plugin")
        jwt_plugin(Q0)
    except Exception as e:
        raise Exception("wasm_load_error: ", e)


def i(a: bytearray, P: List[int]):
    try:
        for Q0 in range(len(a)):
            a[Q0] = a[Q0] ^ P[Q0 % len(P)]
    except Exception:
        return None


def M(a: Any, P: Any):
    try:
        Q0 = crypto.aes_decrypt(a, P)
        return json.loads(Q0)
    except Exception:
        return {}


def z(a: Any):
    return [(a & 4278190080) >> 24, (a & 16711680) >> 16, (a & 65280) >> 8, a & 255]


def get_sources(embed_url: str, site: str):
    global referer
    referer = site
    parts = embed_url.split("/")
    last_part = parts[-1] if parts else ""
    xrax = last_part.split("?")[0] if last_part else ""

    regx = r"https://[a-zA-Z0-9.]*"
    base_url_match = re.match(regx, embed_url)
    if not base_url_match:
        return
    base_url = base_url_match.group(0)
    node_list.image.src = "{}/images/image.png?v=0.0.9".format(base_url)
    test = embed_url.split("/")

    fake_window.xrax = xrax
    fake_window.G = xrax
    canvas.base_url = base_url
    fake_window.origin = base_url
    fake_window.location.origin = base_url
    fake_window.location.href = embed_url

    get_meta(embed_url)

    browser_version = 1878522368

    try:
        V(base_url + "/images/loading.png?v=0.0.9")
        get_sources_url = ""
        if "mega" in base_url:
            get_sources_url = (
                base_url
                + "/"
                + test[3]
                + "/ajax/"
                + test[4]
                + "/getSources?id="
                + getattr(fake_window, "pid", "undefined")
                + "&v="
                + str(fake_window.localStorage.getItem("kversion", "undefined"))
                + "&h="
                + str(fake_window.localStorage.getItem("kid", "undefined"))
                + "&b="
                + str(browser_version)
            )
        else:
            get_sources_url = (
                base_url
                + "/ajax/"
                + test[3]
                + "/"
                + test[4]
                + "/getSources?id="
                + getattr(fake_window, "pid", "undefined")
                + "&v="
                + str(fake_window.localStorage.getItem("kversion", "undefined"))
                + "&h="
                + str(fake_window.localStorage.getItem("kid", "undefined"))
                + "&b="
                + str(browser_version)
            )
        headers = {
            "User-Agent": user_agent,
            "Referer": embed_url,
            "X-Requested-With": "XMLHttpRequest",
        }
        response = requests.get(get_sources_url, headers=headers)
        response.raise_for_status()
        response_dict = response.json()

        Q3 = cast(int, fake_window.localStorage.getItem("kversion", 0))
        Q1 = fake_window.z(int(Q3))
        navigate = getattr(fake_window, "navigate")
        Q5 = navigate()
        q5_byte_arr = bytearray(Q5)
        Q8: Any = None

        if "t" in response_dict and response_dict["t"] != 0:
            i(q5_byte_arr, Q1)
            Q8 = q5_byte_arr
        elif "k" in response_dict:
            Q8 = bytearray(response_dict.k)
            i(Q8, Q1)

        if Q8:
            key = str(base64.b64encode(Q8).decode("utf-8"))
            sources = M(response_dict["sources"], key)
            if sources:
                response_dict["sources"] = sources
        return response_dict

    except Exception as e:
        raise e
