from __future__ import annotations

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

import dill as pickle
import pytest
from inference.core.workflows.core_steps.trackers.sort.v1 import SORTManifest
from inference.core.workflows.execution_engine.entities.base import \
    OutputDefinition
from inference.core.workflows.execution_engine.entities.types import \
    OBJECT_DETECTION_PREDICTION_KIND


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 _validate_basic_structure(outputs):
    """
    Helper to validate the basic expected structure and content of the outputs list.
    This centralizes assertions reused across tests.
    """
    expected_names = ['tracked_detections', 'new_instances', 'already_seen_instances']
    for out_def, expected_name in zip(outputs, expected_names):
        kind = getattr(out_def, 'kind')

def test_describe_outputs_returns_expected_definitions():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    _call__bound__arguments = inspect.signature(SORTManifest.describe_outputs).bind()
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(SORTManifest.describe_outputs, 'tests.inference.unit_tests.test_describe_outputs__unit_test_0', None, 'test_describe_outputs_returns_expected_definitions', 'describe_outputs', '0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    outputs = codeflash_output
    _validate_basic_structure(outputs)

def test_describe_outputs_elements_are_real_instances_and_have_correct_types():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    _call__bound__arguments = inspect.signature(SORTManifest.describe_outputs).bind()
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(SORTManifest.describe_outputs, 'tests.inference.unit_tests.test_describe_outputs__unit_test_0', None, 'test_describe_outputs_elements_are_real_instances_and_have_correct_types', 'describe_outputs', '0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    outputs = codeflash_output
    for out in outputs:
        pass

def test_mutating_returned_list_does_not_modify_future_calls():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    _call__bound__arguments = inspect.signature(SORTManifest.describe_outputs).bind()
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(SORTManifest.describe_outputs, 'tests.inference.unit_tests.test_describe_outputs__unit_test_0', None, 'test_mutating_returned_list_does_not_modify_future_calls', 'describe_outputs', '0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    first = codeflash_output
    removed = first.pop()
    _call__bound__arguments = inspect.signature(SORTManifest.describe_outputs).bind()
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(SORTManifest.describe_outputs, 'tests.inference.unit_tests.test_describe_outputs__unit_test_0', None, 'test_mutating_returned_list_does_not_modify_future_calls', 'describe_outputs', '3', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    second = codeflash_output

def test_mutating_inner_kind_list_does_not_persist_across_calls():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    _call__bound__arguments = inspect.signature(SORTManifest.describe_outputs).bind()
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(SORTManifest.describe_outputs, 'tests.inference.unit_tests.test_describe_outputs__unit_test_0', None, 'test_mutating_inner_kind_list_does_not_persist_across_calls', 'describe_outputs', '0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    first_call = codeflash_output
    first_kind = first_call[0].kind
    first_kind.clear()
    _call__bound__arguments = inspect.signature(SORTManifest.describe_outputs).bind()
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(SORTManifest.describe_outputs, 'tests.inference.unit_tests.test_describe_outputs__unit_test_0', None, 'test_mutating_inner_kind_list_does_not_persist_across_calls', 'describe_outputs', '4', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    second_call = codeflash_output

def test_describe_outputs_returns_new_list_and_new_elements_each_call():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    _call__bound__arguments = inspect.signature(SORTManifest.describe_outputs).bind()
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(SORTManifest.describe_outputs, 'tests.inference.unit_tests.test_describe_outputs__unit_test_0', None, 'test_describe_outputs_returns_new_list_and_new_elements_each_call', 'describe_outputs', '0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    a = codeflash_output
    _call__bound__arguments = inspect.signature(SORTManifest.describe_outputs).bind()
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(SORTManifest.describe_outputs, 'tests.inference.unit_tests.test_describe_outputs__unit_test_0', None, 'test_describe_outputs_returns_new_list_and_new_elements_each_call', 'describe_outputs', '2', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    b = codeflash_output
    a[0].name = 'temporarily_changed_name'

def test_repeated_calls_are_consistent_under_load():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    expected_names = ['tracked_detections', 'new_instances', 'already_seen_instances']
    first_id = None
    seen_different_list_id = False
    for i in range(1000):
        _call__bound__arguments = inspect.signature(SORTManifest.describe_outputs).bind()
        _call__bound__arguments.apply_defaults()
        codeflash_return_value = codeflash_wrap(SORTManifest.describe_outputs, 'tests.inference.unit_tests.test_describe_outputs__unit_test_0', None, 'test_repeated_calls_are_consistent_under_load', 'describe_outputs', '3_0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
        codeflash_output = codeflash_return_value
        outputs = codeflash_output
        if first_id is None:
            first_id = id(outputs)
        elif id(outputs) != first_id:
            seen_different_list_id = True

def test_describe_outputs_content_stability_over_many_calls():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    for _ in range(1000):
        _call__bound__arguments = inspect.signature(SORTManifest.describe_outputs).bind()
        _call__bound__arguments.apply_defaults()
        codeflash_return_value = codeflash_wrap(SORTManifest.describe_outputs, 'tests.inference.unit_tests.test_describe_outputs__unit_test_0', None, 'test_describe_outputs_content_stability_over_many_calls', 'describe_outputs', '0_0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
        codeflash_output = codeflash_return_value
        outputs = codeflash_output
        for o in outputs:
            pass