from __future__ import annotations

import gc
import os
import time

import numpy as np
import pytest
from inference.core.workflows.execution_engine.entities.base import \
    WorkflowImageData


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_basic_copy_preserves_fields_and_returns_new_instance():
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    parent = object()
    origin = WorkflowImageData(parent, base64_image='orig_base64')
    codeflash_return_value = codeflash_wrap(WorkflowImageData.copy_and_replace, 'tests.inference.unit_tests.test_copy_and_replace__unit_test_0', None, 'test_basic_copy_preserves_fields_and_returns_new_instance', 'copy_and_replace', '2', codeflash_loop_index, origin)
    codeflash_output = codeflash_return_value
    copied = codeflash_output

def test_copy_and_replace_replaces_image_fields_when_any_image_key_present():
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    parent = object()
    origin = WorkflowImageData(parent, base64_image='keep_this_base64')
    new_array = np.array([1, 2, 3])
    codeflash_return_value = codeflash_wrap(WorkflowImageData.copy_and_replace, 'tests.inference.unit_tests.test_copy_and_replace__unit_test_0', None, 'test_copy_and_replace_replaces_image_fields_when_any_image_key_present', 'copy_and_replace', '3', codeflash_loop_index, origin, numpy_image=new_array, base64_image=None, image_reference=None)
    codeflash_output = codeflash_return_value
    replaced = codeflash_output

def test_copy_and_replace_raises_if_all_image_representations_are_cleared():
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    parent = object()
    origin = WorkflowImageData(parent, base64_image='present')
    with pytest.raises(ValueError):
        codeflash_return_value = codeflash_wrap(WorkflowImageData.copy_and_replace, 'tests.inference.unit_tests.test_copy_and_replace__unit_test_0', None, 'test_copy_and_replace_raises_if_all_image_representations_are_cleared', 'copy_and_replace', '2_0', codeflash_loop_index, origin, numpy_image=None, base64_image=None, image_reference=None)

def test_parent_and_workflow_root_swapping_when_they_are_identical():
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    original_parent = object()
    origin = WorkflowImageData(original_parent, base64_image='b64')
    new_parent = object()
    codeflash_return_value = codeflash_wrap(WorkflowImageData.copy_and_replace, 'tests.inference.unit_tests.test_copy_and_replace__unit_test_0', None, 'test_parent_and_workflow_root_swapping_when_they_are_identical', 'copy_and_replace', '3', codeflash_loop_index, origin, parent_metadata=new_parent)
    codeflash_output = codeflash_return_value
    replaced = codeflash_output

def test_parent_replacement_does_not_change_workflow_root_if_distinct():
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    parent = object()
    distinct_root = object()
    origin = WorkflowImageData(parent, workflow_root_ancestor_metadata=distinct_root, base64_image='b64')
    new_parent = object()
    codeflash_return_value = codeflash_wrap(WorkflowImageData.copy_and_replace, 'tests.inference.unit_tests.test_copy_and_replace__unit_test_0', None, 'test_parent_replacement_does_not_change_workflow_root_if_distinct', 'copy_and_replace', '4', codeflash_loop_index, origin, parent_metadata=new_parent)
    codeflash_output = codeflash_return_value
    replaced = codeflash_output

def test_workflow_root_replacement_updates_parent_when_they_are_identical():
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    original_parent = object()
    origin = WorkflowImageData(original_parent, base64_image='b64')
    new_root = object()
    codeflash_return_value = codeflash_wrap(WorkflowImageData.copy_and_replace, 'tests.inference.unit_tests.test_copy_and_replace__unit_test_0', None, 'test_workflow_root_replacement_updates_parent_when_they_are_identical', 'copy_and_replace', '3', codeflash_loop_index, origin, workflow_root_ancestor_metadata=new_root)
    codeflash_output = codeflash_return_value
    replaced = codeflash_output

def test_video_metadata_and_image_name_are_updated_if_provided():
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    parent = object()
    origin = WorkflowImageData(parent, base64_image='b64')
    video_meta = {'fps': 30}
    codeflash_return_value = codeflash_wrap(WorkflowImageData.copy_and_replace, 'tests.inference.unit_tests.test_copy_and_replace__unit_test_0', None, 'test_video_metadata_and_image_name_are_updated_if_provided', 'copy_and_replace', '3', codeflash_loop_index, origin, video_metadata=video_meta, image_name='new_name')
    codeflash_output = codeflash_return_value
    replaced = codeflash_output

def test_numpy_array_identity_and_mutation_reflected_in_copy_when_not_replaced():
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    parent = object()
    arr = np.zeros((2, 2), dtype=int)
    origin = WorkflowImageData(parent, numpy_image=arr)
    codeflash_return_value = codeflash_wrap(WorkflowImageData.copy_and_replace, 'tests.inference.unit_tests.test_copy_and_replace__unit_test_0', None, 'test_numpy_array_identity_and_mutation_reflected_in_copy_when_not_replaced', 'copy_and_replace', '3', codeflash_loop_index, origin)
    codeflash_output = codeflash_return_value
    copied = codeflash_output
    arr[0, 0] = 42

def test_constructor_raises_if_no_image_representation_provided():
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    with pytest.raises(ValueError):
        WorkflowImageData(parent_metadata=object())
    with pytest.raises(ValueError):
        WorkflowImageData(parent_metadata=object(), numpy_image=None)

def test_large_scale_many_sequential_copies_update_image_name_correctly():
    np.random.seed(42)
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    parent = object()
    origin = WorkflowImageData(parent, base64_image='persistent_base64')
    current = origin
    for i in range(1000):
        codeflash_return_value = codeflash_wrap(WorkflowImageData.copy_and_replace, 'tests.inference.unit_tests.test_copy_and_replace__unit_test_0', None, 'test_large_scale_many_sequential_copies_update_image_name_correctly', 'copy_and_replace', '3_0', codeflash_loop_index, current, image_name=f'name_{i}')
        codeflash_output = codeflash_return_value
        current = codeflash_output