# -*- coding: utf-8 -*-
# Copyright © 2023 Contrast Security, Inc.
# See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
"""
Instrumentation for genshi globals function. Essentially what happens here is when
genshi calls the builtin eval function to eval the template code (and perform var lookup)
a custom mechanism is used in the genshi eval.py file. As a result we needed to patch
globals in order to inject our contrast__operator for modulo string operations.
"""

from contrast_vendor.wrapt import register_post_import_hook

from contrast.utils.patch_utils import build_and_apply_patch
from contrast.utils.patch_utils import wrap_and_watermark
from contrast_rewriter import populate_operator_module


GENSHI_TEMPALTE_ENGINE_EVAL_MODULE = "genshi.template.eval"


def build_genshi_eval_globals_patch(orig_func, _, rule_applicator):
    del rule_applicator

    def genshi_eval_globals_patch(wrapped, instance, args, kwargs):
        if len(args) > 0 and isinstance(args[0], dict):
            populate_operator_module(args[0])

        return orig_func(args)

    return wrap_and_watermark(orig_func, genshi_eval_globals_patch)


def patch_genshi_globals(genshi_eval_module):
    build_and_apply_patch(
        genshi_eval_module.LookupBase,
        "globals",
        build_genshi_eval_globals_patch,
        (None,),
    )


def register_patches():
    register_post_import_hook(patch_genshi_globals, GENSHI_TEMPALTE_ENGINE_EVAL_MODULE)
