from __future__ import annotations

import base64
import gc
import os
import time
from unittest.mock import Mock

import numpy as np
import pytest
from inference.core.workflows.execution_engine.entities.base import \
    WorkflowImageData
from inference.enterprise.workflows.enterprise_blocks.sinks.event_writer.v1 import \
    _build_image_entry


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

@pytest.fixture
def sample_base64_image():
    """Create a valid base64-encoded test image."""
    img = np.zeros((10, 10, 3), dtype=np.uint8)
    import cv2
    _, buffer = cv2.imencode('.jpg', img)
    b64_str = base64.b64encode(buffer).decode('ascii')
    return b64_str

@pytest.fixture
def sample_workflow_image_data(sample_base64_image):
    """Create a real WorkflowImageData instance with base64 image."""
    from inference.core.workflows.execution_engine.entities.base import \
        ImageParentMetadata
    parent_metadata = ImageParentMetadata(parent_id='test_image_1')
    return WorkflowImageData(parent_metadata=parent_metadata, base64_image=sample_base64_image)

@pytest.fixture
def sample_workflow_image_data_with_numpy(sample_base64_image):
    """Create a real WorkflowImageData instance with numpy image."""
    from inference.core.workflows.execution_engine.entities.base import \
        ImageParentMetadata
    parent_metadata = ImageParentMetadata(parent_id='test_image_2')
    img = np.zeros((10, 10, 3), dtype=np.uint8)
    return WorkflowImageData(parent_metadata=parent_metadata, numpy_image=img, base64_image=sample_base64_image)

def test_build_image_entry_minimal_required_args(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that _build_image_entry works with only required output_image argument.'
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_minimal_required_args', '_build_image_entry', '1', codeflash_loop_index, output_image=sample_workflow_image_data)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_with_input_image(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that _build_image_entry correctly includes input_image when provided.'
    input_img = sample_workflow_image_data
    output_img = sample_workflow_image_data
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_with_input_image', '_build_image_entry', '3', codeflash_loop_index, output_image=output_img, input_image=input_img)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_with_label(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that _build_image_entry correctly includes image_label when provided.'
    label = 'test_label_123'
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_with_label', '_build_image_entry', '2', codeflash_loop_index, output_image=sample_workflow_image_data, image_label=label)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_with_all_optional_strings(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test _build_image_entry with output_image, input_image, and label all provided.'
    input_img = sample_workflow_image_data
    output_img = sample_workflow_image_data
    label = 'my_image_label'
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_with_all_optional_strings', '_build_image_entry', '4', codeflash_loop_index, output_image=output_img, input_image=input_img, image_label=label)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_with_empty_object_detections(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that empty object_detections list does not add objectDetections key.'
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_with_empty_object_detections', '_build_image_entry', '1', codeflash_loop_index, output_image=sample_workflow_image_data, object_detections=None)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_with_empty_classifications(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that empty classifications does not add classifications key.'
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_with_empty_classifications', '_build_image_entry', '1', codeflash_loop_index, output_image=sample_workflow_image_data, classifications=None)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_with_empty_instance_segmentations(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that empty instance_segmentations does not add instanceSegmentations key.'
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_with_empty_instance_segmentations', '_build_image_entry', '1', codeflash_loop_index, output_image=sample_workflow_image_data, instance_segmentations=None)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_with_empty_keypoint_detections(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that empty keypoint_detections does not add keypoints key.'
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_with_empty_keypoint_detections', '_build_image_entry', '1', codeflash_loop_index, output_image=sample_workflow_image_data, keypoint_detections=None)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_returns_dict(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that _build_image_entry always returns a dictionary.'
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_returns_dict', '_build_image_entry', '1', codeflash_loop_index, output_image=sample_workflow_image_data)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_base64_image_is_string(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that base64Image value is a string.'
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_base64_image_is_string', '_build_image_entry', '1', codeflash_loop_index, output_image=sample_workflow_image_data)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_with_none_input_image(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that None input_image does not add inputBase64Image key.'
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_with_none_input_image', '_build_image_entry', '1', codeflash_loop_index, output_image=sample_workflow_image_data, input_image=None)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_with_none_label(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that None image_label does not add label key.'
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_with_none_label', '_build_image_entry', '1', codeflash_loop_index, output_image=sample_workflow_image_data, image_label=None)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_with_empty_string_label(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that empty string image_label is preserved (not treated as None).'
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_with_empty_string_label', '_build_image_entry', '1', codeflash_loop_index, output_image=sample_workflow_image_data, image_label='')
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_with_special_characters_in_label(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that special characters in label are preserved.'
    special_label = 'label_with_@#$%_special chars!@#$'
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_with_special_characters_in_label', '_build_image_entry', '2', codeflash_loop_index, output_image=sample_workflow_image_data, image_label=special_label)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_with_unicode_label(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that unicode characters in label are handled correctly.'
    unicode_label = 'label_with_emoji_🎉_and_unicode_é'
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_with_unicode_label', '_build_image_entry', '2', codeflash_loop_index, output_image=sample_workflow_image_data, image_label=unicode_label)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_with_very_long_label(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that very long labels are handled correctly.'
    long_label = 'x' * 10000
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_with_very_long_label', '_build_image_entry', '2', codeflash_loop_index, output_image=sample_workflow_image_data, image_label=long_label)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_detections_converter_exception_handling(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that invalid object_detections object that raises exception is handled gracefully.'
    invalid_detections = Mock()
    invalid_detections.xyxy = Mock(side_effect=RuntimeError('Access error'))
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_detections_converter_exception_handling', '_build_image_entry', '3', codeflash_loop_index, output_image=sample_workflow_image_data, object_detections=invalid_detections)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_classifications_converter_exception_handling(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that invalid classifications object that raises exception is handled gracefully.'
    invalid_classifications = Mock()
    invalid_classifications.data = Mock(side_effect=RuntimeError('Access error'))
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_classifications_converter_exception_handling', '_build_image_entry', '3', codeflash_loop_index, output_image=sample_workflow_image_data, classifications=invalid_classifications)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_instance_segmentations_exception_handling(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that invalid instance_segmentations raises exception is handled gracefully.'
    invalid_segmentations = Mock()
    invalid_segmentations.xyxy = Mock(side_effect=RuntimeError('Access error'))
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_instance_segmentations_exception_handling', '_build_image_entry', '3', codeflash_loop_index, output_image=sample_workflow_image_data, instance_segmentations=invalid_segmentations)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_keypoints_exception_handling(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that invalid keypoint_detections that raises exception is handled gracefully.'
    invalid_keypoints = Mock()
    invalid_keypoints.xyxy = Mock(side_effect=RuntimeError('Access error'))
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_keypoints_exception_handling', '_build_image_entry', '3', codeflash_loop_index, output_image=sample_workflow_image_data, keypoint_detections=invalid_keypoints)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_with_multiple_different_images(sample_workflow_image_data, sample_workflow_image_data_with_numpy):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that different input and output images produce correct result.'
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_with_multiple_different_images', '_build_image_entry', '1', codeflash_loop_index, output_image=sample_workflow_image_data, input_image=sample_workflow_image_data_with_numpy)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_dict_not_modified_on_multiple_calls(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    "Test that calling _build_image_entry multiple times doesn't cause side effects."
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_dict_not_modified_on_multiple_calls', '_build_image_entry', '1', codeflash_loop_index, output_image=sample_workflow_image_data)
    codeflash_output = codeflash_return_value
    result1 = codeflash_output
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_dict_not_modified_on_multiple_calls', '_build_image_entry', '3', codeflash_loop_index, output_image=sample_workflow_image_data)
    codeflash_output = codeflash_return_value
    result2 = codeflash_output

def test_build_image_entry_with_numeric_label(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that numeric label is accepted and converted to string if needed.'
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_with_numeric_label', '_build_image_entry', '1', codeflash_loop_index, output_image=sample_workflow_image_data, image_label=123)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_preserves_base64_content_integrity(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that base64Image content is not modified during building.'
    original_base64 = sample_workflow_image_data.base64_image
    codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_preserves_base64_content_integrity', '_build_image_entry', '2', codeflash_loop_index, output_image=sample_workflow_image_data)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_build_image_entry_performance_many_calls(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that _build_image_entry performs reasonably with many repeated calls.'
    results = []
    for i in range(1000):
        codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_performance_many_calls', '_build_image_entry', '2_0', codeflash_loop_index, output_image=sample_workflow_image_data, image_label=f'label_{i}')
        codeflash_output = codeflash_return_value
        result = codeflash_output
        results.append(result)
    for i, result in enumerate(results):
        pass

def test_build_image_entry_with_many_variations(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test building entries with various combinations of parameters.'
    results = []
    for i in range(100):
        codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_with_many_variations', '_build_image_entry', '2_0', codeflash_loop_index, output_image=sample_workflow_image_data, image_label=f'batch_{i % 10}_item_{i}')
        codeflash_output = codeflash_return_value
        result = codeflash_output
        results.append(result)

def test_build_image_entry_scalability_with_large_labels(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test handling of progressively larger labels to assess scalability.'
    for size in [100, 1000, 10000, 100000]:
        large_label = 'x' * size
        codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_scalability_with_large_labels', '_build_image_entry', '1_1', codeflash_loop_index, output_image=sample_workflow_image_data, image_label=large_label)
        codeflash_output = codeflash_return_value
        result = codeflash_output

def test_build_image_entry_consistency_with_no_predictions(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test that multiple calls with None predictions produce consistent results.'
    results = []
    for _ in range(100):
        codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_consistency_with_no_predictions', '_build_image_entry', '2_0', codeflash_loop_index, output_image=sample_workflow_image_data, object_detections=None, classifications=None, instance_segmentations=None, keypoint_detections=None)
        codeflash_output = codeflash_return_value
        result = codeflash_output
        results.append(result)

def test_build_image_entry_all_parameters_at_scale(sample_workflow_image_data):
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test building entries with all parameters specified 100 times.'
    results = []
    for i in range(100):
        codeflash_return_value = codeflash_wrap(_build_image_entry, 'tests.inference.unit_tests.test__build_image_entry__unit_test_1', None, 'test_build_image_entry_all_parameters_at_scale', '_build_image_entry', '2_0', codeflash_loop_index, output_image=sample_workflow_image_data, input_image=sample_workflow_image_data, image_label=f'comprehensive_test_{i}', object_detections=None, classifications=None, instance_segmentations=None, keypoint_detections=None)
        codeflash_output = codeflash_return_value
        result = codeflash_output
        results.append(result)
    for i, result in enumerate(results):
        pass