from __future__ import annotations

import gc
import os
import time

import pytest
from inference.core.workflows.core_steps.common.query_language.errors import \
    InvalidInputTypeError
from inference.core.workflows.core_steps.common.query_language.operations.sequences.base import \
    sequence_apply


def codeflash_wrap(codeflash_wrapped, codeflash_test_module_name, codeflash_test_class_name, codeflash_test_name, codeflash_function_name, codeflash_line_id, codeflash_loop_index, *args, **kwargs):
    test_id = f'{codeflash_test_module_name}:{codeflash_test_class_name}:{codeflash_test_name}:{codeflash_line_id}:{codeflash_loop_index}'
    if not hasattr(codeflash_wrap, 'index'):
        codeflash_wrap.index = {}
    if test_id in codeflash_wrap.index:
        codeflash_wrap.index[test_id] += 1
    else:
        codeflash_wrap.index[test_id] = 0
    codeflash_test_index = codeflash_wrap.index[test_id]
    invocation_id = f'{codeflash_line_id}_{codeflash_test_index}'
    test_stdout_tag = f"{codeflash_test_module_name}:{(codeflash_test_class_name + '.' if codeflash_test_class_name else '')}{codeflash_test_name}:{codeflash_function_name}:{codeflash_loop_index}:{invocation_id}"
    print(f'!$######{test_stdout_tag}######$!')
    exception = None
    gc.disable()
    try:
        counter = time.perf_counter_ns()
        return_value = codeflash_wrapped(*args, **kwargs)
        codeflash_duration = time.perf_counter_ns() - counter
    except Exception as e:
        codeflash_duration = time.perf_counter_ns() - counter
        exception = e
    gc.enable()
    print(f'!######{test_stdout_tag}:{codeflash_duration}######!')
    if exception:
        raise exception
    return return_value

def test_sequence_apply_with_list_and_kwargs():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    values = [1, 2, 3]

    def add_fn(x, add=0):
        return x + add
    codeflash_return_value = codeflash_wrap(sequence_apply, 'tests.inference.unit_tests.test_sequence_apply__unit_test_0', None, 'test_sequence_apply_with_list_and_kwargs', 'sequence_apply', '2', codeflash_loop_index, values, add_fn, execution_context='basic_ctx', add=10)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_sequence_apply_with_tuple_and_string_suffix():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    values = ('apple', 'banana')

    def suffix_fn(s, suffix=''):
        return s + suffix
    codeflash_return_value = codeflash_wrap(sequence_apply, 'tests.inference.unit_tests.test_sequence_apply__unit_test_0', None, 'test_sequence_apply_with_tuple_and_string_suffix', 'sequence_apply', '2', codeflash_loop_index, values, suffix_fn, execution_context='tuple_ctx', suffix='_X')
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_sequence_apply_with_empty_sequence_returns_empty_list():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    values = []

    def identity(x):
        return x
    codeflash_return_value = codeflash_wrap(sequence_apply, 'tests.inference.unit_tests.test_sequence_apply__unit_test_0', None, 'test_sequence_apply_with_empty_sequence_returns_empty_list', 'sequence_apply', '2', codeflash_loop_index, values, identity, execution_context='empty_ctx')
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_sequence_apply_iterates_string_characters():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    value = 'abC'

    def to_lower(ch):
        return ch.lower()
    codeflash_return_value = codeflash_wrap(sequence_apply, 'tests.inference.unit_tests.test_sequence_apply__unit_test_0', None, 'test_sequence_apply_iterates_string_characters', 'sequence_apply', '2', codeflash_loop_index, value, to_lower, execution_context='string_ctx')
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_sequence_apply_with_generator_input():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    gen = (i * 2 for i in range(3))

    def inc(x, inc_by=1):
        return x + inc_by
    codeflash_return_value = codeflash_wrap(sequence_apply, 'tests.inference.unit_tests.test_sequence_apply__unit_test_0', None, 'test_sequence_apply_with_generator_input', 'sequence_apply', '2', codeflash_loop_index, gen, inc, execution_context='gen_ctx', inc_by=1)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_sequence_apply_with_dict_iterates_keys_in_insertion_order():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    d = {'first': 1, 'second': 2}

    def tag_key(k, tag=''):
        return f'{k}{tag}'
    codeflash_return_value = codeflash_wrap(sequence_apply, 'tests.inference.unit_tests.test_sequence_apply__unit_test_0', None, 'test_sequence_apply_with_dict_iterates_keys_in_insertion_order', 'sequence_apply', '2', codeflash_loop_index, d, tag_key, execution_context='dict_ctx', tag='_K')
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_sequence_apply_with_none_in_sequence_and_special_handling():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    values = [None, 2]

    def handle_none(v):
        return 'NONE' if v is None else v * 2
    codeflash_return_value = codeflash_wrap(sequence_apply, 'tests.inference.unit_tests.test_sequence_apply__unit_test_0', None, 'test_sequence_apply_with_none_in_sequence_and_special_handling', 'sequence_apply', '2', codeflash_loop_index, values, handle_none, execution_context='none_ctx')
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_sequence_apply_with_non_iterable_raises_invalid_input_type_error_and_contains_context():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    non_iterable = 42
    with pytest.raises(InvalidInputTypeError) as excinfo:
        codeflash_return_value = codeflash_wrap(sequence_apply, 'tests.inference.unit_tests.test_sequence_apply__unit_test_0', None, 'test_sequence_apply_with_non_iterable_raises_invalid_input_type_error_and_contains_context', 'sequence_apply', '1_0', codeflash_loop_index, non_iterable, lambda x: x, execution_context='non_iter_ctx')
    exc = excinfo.value

def test_sequence_apply_wraps_typeerror_and_valueerror_from_element_processing_into_invalid_input_type_error():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    values = [1, 2, 3]

    def sometimes_type_error(x):
        if x == 2:
            raise TypeError('bad type')
        return x
    with pytest.raises(InvalidInputTypeError) as excinfo_type:
        codeflash_return_value = codeflash_wrap(sequence_apply, 'tests.inference.unit_tests.test_sequence_apply__unit_test_0', None, 'test_sequence_apply_wraps_typeerror_and_valueerror_from_element_processing_into_invalid_input_type_error', 'sequence_apply', '2_0', codeflash_loop_index, values, sometimes_type_error, execution_context='wrap_ctx')
    exc_type = excinfo_type.value

    def sometimes_value_error(x):
        if x == 3:
            raise ValueError('bad value')
        return x
    with pytest.raises(InvalidInputTypeError) as excinfo_value:
        codeflash_return_value = codeflash_wrap(sequence_apply, 'tests.inference.unit_tests.test_sequence_apply__unit_test_0', None, 'test_sequence_apply_wraps_typeerror_and_valueerror_from_element_processing_into_invalid_input_type_error', 'sequence_apply', '5_0', codeflash_loop_index, values, sometimes_value_error, execution_context='wrap_ctx_val')
    exc_value = excinfo_value.value

def test_sequence_apply_does_not_swallow_other_exceptions_runtimeerror_propagates():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    values = [0, 1]

    def sometimes_runtime_error(x):
        if x == 1:
            raise RuntimeError('boom')
        return x
    with pytest.raises(RuntimeError):
        codeflash_return_value = codeflash_wrap(sequence_apply, 'tests.inference.unit_tests.test_sequence_apply__unit_test_0', None, 'test_sequence_apply_does_not_swallow_other_exceptions_runtimeerror_propagates', 'sequence_apply', '2_0', codeflash_loop_index, values, sometimes_runtime_error, execution_context='runtime_ctx')

def test_sequence_apply_large_scale_simple_mapping():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    n = 1000
    values = list(range(n))

    def add_offset(x, offset=0):
        return x + offset
    offset = 1000
    codeflash_return_value = codeflash_wrap(sequence_apply, 'tests.inference.unit_tests.test_sequence_apply__unit_test_0', None, 'test_sequence_apply_large_scale_simple_mapping', 'sequence_apply', '4', codeflash_loop_index, values, add_offset, execution_context='large_ctx', offset=offset)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_sequence_apply_large_scale_with_generator_1000_elements():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    n = 1000
    gen = (i * 3 for i in range(n))

    def times_two(x):
        return x * 2
    codeflash_return_value = codeflash_wrap(sequence_apply, 'tests.inference.unit_tests.test_sequence_apply__unit_test_0', None, 'test_sequence_apply_large_scale_with_generator_1000_elements', 'sequence_apply', '3', codeflash_loop_index, gen, times_two, execution_context='large_gen_ctx')
    codeflash_output = codeflash_return_value
    result = codeflash_output