from __future__ import annotations

import gc
import inspect
import os
import time
from pathlib import Path

import dill as pickle
import pytest
from inference.enterprise.workflows.enterprise_blocks.sinks.event_writer.v1 import \
    _build_event_data


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}######!')
    iteration = os.environ['CODEFLASH_TEST_ITERATION']
    with Path('{codeflash_run_tmp_dir_client_side}', f'test_return_values_{iteration}.bin').open('ab') as f:
        pickled_values = pickle.dumps((args, kwargs, exception)) if exception else pickle.dumps((args, kwargs, return_value))
        _test_name = f"{codeflash_test_module_name}:{(codeflash_test_class_name + '.' if codeflash_test_class_name else '')}{codeflash_test_name}:{codeflash_function_name}:{codeflash_line_id}".encode('ascii')
        f.write(len(_test_name).to_bytes(4, byteorder='big'))
        f.write(_test_name)
        f.write(codeflash_duration.to_bytes(8, byteorder='big'))
        f.write(len(pickled_values).to_bytes(4, byteorder='big'))
        f.write(pickled_values)
        f.write(codeflash_loop_index.to_bytes(8, byteorder='big'))
        f.write(len(invocation_id).to_bytes(4, byteorder='big'))
        f.write(invocation_id.encode('ascii'))
    if exception:
        raise exception
    return return_value

def test_quality_check_basic_mapping_and_values():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    _call__bound__arguments = inspect.signature(_build_event_data).bind(event_schema='quality_check', qc_result='pass', external_id='QC123')
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_build_event_data, 'tests.inference.unit_tests.test__build_event_data__unit_test_0', None, 'test_quality_check_basic_mapping_and_values', '_build_event_data', '0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_inventory_count_basic_mapping_and_values():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    _call__bound__arguments = inspect.signature(_build_event_data).bind(event_schema='inventory_count', location='Warehouse A', item_count=42, item_type='widget', external_id='INV-42')
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_build_event_data, 'tests.inference.unit_tests.test__build_event_data__unit_test_0', None, 'test_inventory_count_basic_mapping_and_values', '_build_event_data', '0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_safety_alert_basic_mapping_and_values():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    _call__bound__arguments = inspect.signature(_build_event_data).bind(event_schema='safety_alert', alert_type='fire', severity='high', alert_description='Smoke detected in zone 3', external_id='ALERT-001')
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_build_event_data, 'tests.inference.unit_tests.test__build_event_data__unit_test_0', None, 'test_safety_alert_basic_mapping_and_values', '_build_event_data', '0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_custom_schema_basic_mapping_and_values():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    _call__bound__arguments = inspect.signature(_build_event_data).bind(event_schema='custom', external_id='CUST-9', custom_value='opaque-payload')
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_build_event_data, 'tests.inference.unit_tests.test__build_event_data__unit_test_0', None, 'test_custom_schema_basic_mapping_and_values', '_build_event_data', '0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_strip_none_values_removes_only_nones():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    _call__bound__arguments = inspect.signature(_build_event_data).bind(event_schema='inventory_count', location=None, item_count=0, item_type='', external_id=None)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_build_event_data, 'tests.inference.unit_tests.test__build_event_data__unit_test_0', None, 'test_strip_none_values_removes_only_nones', '_build_event_data', '0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    res = codeflash_output

def test_all_none_values_yield_empty_dict_for_schema():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    _call__bound__arguments = inspect.signature(_build_event_data).bind(event_schema='quality_check', qc_result=None, external_id=None)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_build_event_data, 'tests.inference.unit_tests.test__build_event_data__unit_test_0', None, 'test_all_none_values_yield_empty_dict_for_schema', '_build_event_data', '0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    res_qc = codeflash_output
    _call__bound__arguments = inspect.signature(_build_event_data).bind(event_schema='safety_alert', alert_type=None, severity=None, alert_description=None, external_id=None)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_build_event_data, 'tests.inference.unit_tests.test__build_event_data__unit_test_0', None, 'test_all_none_values_yield_empty_dict_for_schema', '_build_event_data', '2', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    res_alert = codeflash_output
    _call__bound__arguments = inspect.signature(_build_event_data).bind(event_schema='custom', external_id=None, custom_value=None)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_build_event_data, 'tests.inference.unit_tests.test__build_event_data__unit_test_0', None, 'test_all_none_values_yield_empty_dict_for_schema', '_build_event_data', '4', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    res_custom = codeflash_output

def test_unknown_schema_ignores_provided_values_and_returns_empty_dict():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    _call__bound__arguments = inspect.signature(_build_event_data).bind(event_schema='nonexistent_schema', qc_result='pass', external_id='SHOULD_BE_IGNORED', location='Nowhere', item_count=7, alert_type='none', custom_value='ignored')
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_build_event_data, 'tests.inference.unit_tests.test__build_event_data__unit_test_0', None, 'test_unknown_schema_ignores_provided_values_and_returns_empty_dict', '_build_event_data', '0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    res = codeflash_output

def test_special_characters_and_whitespace_preserved():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    special_str = 'Line1\nLine2\t€ – emoji: 😊'
    _call__bound__arguments = inspect.signature(_build_event_data).bind(event_schema='safety_alert', alert_type=special_str, severity='low', alert_description='Contains newline\nand\ttab', external_id='SPECIAL-♥')
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_build_event_data, 'tests.inference.unit_tests.test__build_event_data__unit_test_0', None, 'test_special_characters_and_whitespace_preserved', '_build_event_data', '1', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    res = codeflash_output

def test_large_scale_many_calls_alternating_schemas():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    count = 1000
    for i in range(count):
        if i % 4 == 0:
            expected = {'result': f'r{i}', 'externalId': f'id{i}'}
            _call__bound__arguments = inspect.signature(_build_event_data).bind('quality_check', qc_result=f'r{i}', external_id=f'id{i}')
            _call__bound__arguments.apply_defaults()
            codeflash_return_value = codeflash_wrap(_build_event_data, 'tests.inference.unit_tests.test__build_event_data__unit_test_0', None, 'test_large_scale_many_calls_alternating_schemas', '_build_event_data', '1_0_1', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
            codeflash_output = codeflash_return_value
            out = codeflash_output
        elif i % 4 == 1:
            expected = {'location': f'loc{i}', 'itemCount': i, 'itemType': f'type{i}', 'externalId': f'id{i}'}
            _call__bound__arguments = inspect.signature(_build_event_data).bind('inventory_count', location=f'loc{i}', item_count=i, item_type=f'type{i}', external_id=f'id{i}')
            _call__bound__arguments.apply_defaults()
            codeflash_return_value = codeflash_wrap(_build_event_data, 'tests.inference.unit_tests.test__build_event_data__unit_test_0', None, 'test_large_scale_many_calls_alternating_schemas', '_build_event_data', '1_0_0_1', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
            codeflash_output = codeflash_return_value
            out = codeflash_output
        elif i % 4 == 2:
            expected = {'alertType': f'a{i}', 'severity': 'medium', 'description': f'desc{i}', 'externalId': f'id{i}'}
            _call__bound__arguments = inspect.signature(_build_event_data).bind('safety_alert', alert_type=f'a{i}', severity='medium', alert_description=f'desc{i}', external_id=f'id{i}')
            _call__bound__arguments.apply_defaults()
            codeflash_return_value = codeflash_wrap(_build_event_data, 'tests.inference.unit_tests.test__build_event_data__unit_test_0', None, 'test_large_scale_many_calls_alternating_schemas', '_build_event_data', '1_0_0_0_1', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
            codeflash_output = codeflash_return_value
            out = codeflash_output
        else:
            expected = {'externalId': f'id{i}', 'value': f'v{i}'}
            _call__bound__arguments = inspect.signature(_build_event_data).bind('custom', external_id=f'id{i}', custom_value=f'v{i}')
            _call__bound__arguments.apply_defaults()
            codeflash_return_value = codeflash_wrap(_build_event_data, 'tests.inference.unit_tests.test__build_event_data__unit_test_0', None, 'test_large_scale_many_calls_alternating_schemas', '_build_event_data', '1_0_0_0_1', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
            codeflash_output = codeflash_return_value
            out = codeflash_output

def test_large_scale_many_distinct_inputs_list_processing():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    ids = [f'EXT-{n}' for n in range(1000)]
    for idx, eid in enumerate(ids):
        _call__bound__arguments = inspect.signature(_build_event_data).bind('inventory_count', location=f'Loc-{idx}', item_count=idx, item_type='type', external_id=eid)
        _call__bound__arguments.apply_defaults()
        codeflash_return_value = codeflash_wrap(_build_event_data, 'tests.inference.unit_tests.test__build_event_data__unit_test_0', None, 'test_large_scale_many_distinct_inputs_list_processing', '_build_event_data', '1_0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
        codeflash_output = codeflash_return_value
        out = codeflash_output