"""Profile the cache key generation to find hotspots"""

import cProfile
import pstats
from inspect import Parameter, signature


def build_cache_key_eval(method, cache_args):
    """Current implementation using eval"""
    args = ", ".join(
        str(params.replace(annotation=Parameter.empty))
        for params in signature(method).parameters.values()
    )
    values = ["self._name", "method", *cache_args]
    code = (
        f"lambda {args}: ({''.join(a for arg in values for a in (arg, ','))})"
    )
    return eval(code, {"method": method})


class MockModel:
    _name = "test.model"

    def simple_method(self, arg1, arg2):
        return arg1 + arg2


# Profile the creation overhead
profiler = cProfile.Profile()
profiler.enable()

for i in range(10_000):
    _ = build_cache_key_eval(MockModel.simple_method, ["arg1", "arg2"])

profiler.disable()

# Print stats
stats = pstats.Stats(profiler)
stats.sort_stats("cumulative")
print("=== Top 20 functions by cumulative time ===")
stats.print_stats(20)
