"""Benchmark for split_multichar optimization (Target 6)"""

import sys
import time
from functools import reduce


# Original implementation (recursive)
def split_multichar_original(ss, chars):
    """Original recursive implementation"""
    if len(chars) == 0:
        return ss
    c = chars.pop()
    ss = reduce(lambda x, y: x + y, (x.split(c) for x in ss))
    return split_multichar_original(ss, chars)


# Optimized implementation (iterative, no list recreation)
def split_multichar_optimized(ss, chars):
    """Optimized iterative implementation"""
    for c in chars:
        result = []
        for s in ss:
            result.extend(s.split(c))
        ss = result
    return ss


def benchmark(func, ss, chars, iterations=10000):
    """Benchmark a split_multichar implementation"""
    total_time = 0
    for _ in range(iterations):
        # Make a copy of inputs since original mutates chars
        ss_copy = ss.copy()
        chars_copy = chars.copy()

        start = time.perf_counter()
        result = func(ss_copy, chars_copy)
        total_time += time.perf_counter() - start

    avg_time = total_time / iterations
    return avg_time, result


def main():
    # Test cases matching real usage in basedatatypes.py
    test_cases = [
        # Line 70: key_path_str split on ".[]"
        (["a.string[0].with_separators"], list(".[]")),
        # Line 96: s split on "_"
        (["layout_xaxis_title"], list("_")),
        # More complex case
        (["trace.marker[0].color_array[5]"], list(".[]_")),
        # Multiple strings
        (["a.b.c", "x[0].y", "foo_bar_baz"], list(".[]_")),
    ]

    print("Benchmarking split_multichar implementations")
    print("=" * 60)

    for i, (ss, chars) in enumerate(test_cases, 1):
        print(f"\nTest case {i}: {ss} with chars {chars}")

        # Benchmark original
        orig_time, orig_result = benchmark(split_multichar_original, ss, chars)

        # Benchmark optimized
        opt_time, opt_result = benchmark(split_multichar_optimized, ss, chars)

        # Verify results match
        if orig_result != opt_result:
            print("  ERROR: Results don't match!")
            print(f"    Original: {orig_result}")
            print(f"    Optimized: {opt_result}")
            sys.exit(1)

        # Report results
        speedup = orig_time / opt_time
        print(f"  Result: {opt_result}")
        print(f"  Original:  {orig_time * 1e6:.2f} µs")
        print(f"  Optimized: {opt_time * 1e6:.2f} µs")
        print(f"  Speedup:   {speedup:.2f}x")

    print("\n" + "=" * 60)
    print("All tests passed!")


if __name__ == "__main__":
    main()
