from __future__ import annotations

import gc
import inspect
import logging
import os
import time
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from unittest.mock import MagicMock, patch

import dill as pickle
import pytest
from inference.core.exceptions import WorkspaceLoadError
from inference.core.workflows.core_steps.composition.workflow_caller.v1 import (
    _RESOLVED_WORKFLOW_OUTPUTS, MAX_WORKFLOW_CALL_DEPTH,
    WORKFLOW_CALL_CHAIN_HEADER, WorkflowCallerBlockV1, _build_kind_name_map,
    _build_kinds_deserializers_map, _deserialize_output_value, _make_cache_key,
    _resolve_output_kinds_for_run, build_workflow_inputs, call_workflow,
    execute_workflow_request)
from inference.core.workflows.execution_engine.entities.base import \
    WorkflowImageData
from inference.core.workflows.execution_engine.entities.types import (
    WILDCARD_KIND, 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 test_workflow_caller_block_v1_init_with_api_key():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test WorkflowCallerBlockV1 initialization with API key.'
    api_key = 'test_api_key_123'
    block = WorkflowCallerBlockV1(api_key=api_key)

def test_workflow_caller_block_v1_init_with_call_chain():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test WorkflowCallerBlockV1 initialization with existing call chain.'
    api_key = 'test_key'
    call_chain = 'workflow_a,workflow_b'
    block = WorkflowCallerBlockV1(api_key=api_key, workflow_call_chain=call_chain)

def test_workflow_caller_block_v1_init_without_api_key():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test WorkflowCallerBlockV1 initialization without API key.'
    block = WorkflowCallerBlockV1(api_key=None)

def test_make_cache_key_with_workflow_id_only():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test cache key generation with workflow_id only.'
    key = _make_cache_key(workflow_id='test_workflow')

def test_make_cache_key_with_workflow_id_and_version():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test cache key generation with workflow_id and version_id.'
    key = _make_cache_key(workflow_id='test_workflow', workflow_version_id='v1')

def test_build_workflow_inputs_with_simple_dict():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test build_workflow_inputs with simple dictionary input.'
    inputs = {'param1': 'value1', 'param2': 42, 'param3': True}
    result = build_workflow_inputs(inputs)

def test_build_workflow_inputs_with_nested_structures():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test build_workflow_inputs with nested lists and dicts.'
    inputs = {'nested_dict': {'key': 'value'}, 'nested_list': [1, 2, 3], 'mixed': {'inner_list': [1, 2], 'inner_value': 'test'}}
    result = build_workflow_inputs(inputs)

def test_resolve_output_kinds_for_run_returns_none_when_no_definitions():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test _resolve_output_kinds_for_run returns None when no output definitions exist.'
    _RESOLVED_WORKFLOW_OUTPUTS.clear()
    result = _resolve_output_kinds_for_run(output_definitions={}, workflow_id='unknown_workflow', workflow_version_id=None)

def test_deserialize_output_value_with_none_value():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test _deserialize_output_value returns None when raw_value is None.'
    result = _deserialize_output_value(output_name='test_output', raw_value=None, output_kinds=[WILDCARD_KIND], deserializers={})

def test_deserialize_output_value_with_wildcard_kind():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test _deserialize_output_value returns raw value for WILDCARD_KIND.'
    raw_value = {'data': 'test'}
    result = _deserialize_output_value(output_name='test_output', raw_value=raw_value, output_kinds=[WILDCARD_KIND], deserializers={})

def test_call_workflow_with_empty_call_chain():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test call_workflow with empty call chain.'
    with patch('inference.core.workflows.core_steps.composition.workflow_caller.v1.execute_workflow_request') as mock_execute:
        mock_execute.return_value = (False, 'Success', {'output': 'value'})
        error_status, message, result = call_workflow(api_key='test_key', workspace_name='test_workspace', workflow_id='wf1', inputs={'input': 'data'}, request_timeout=30, call_chain='', workflow_version_id=None)
        mock_execute.assert_called_once()
        args, kwargs = mock_execute.call_args

def test_call_workflow_detects_circular_reference():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test call_workflow detects circular workflow calls.'
    error_status, message, result = call_workflow(api_key='test_key', workspace_name='test_workspace', workflow_id='wf1', inputs={'input': 'data'}, request_timeout=30, call_chain='wf1,wf2', workflow_version_id=None)

def test_call_workflow_detects_max_depth_exceeded():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test call_workflow detects when max call depth is exceeded.'
    chain_entries = [f'wf{i}' for i in range(MAX_WORKFLOW_CALL_DEPTH)]
    call_chain = ','.join(chain_entries)
    error_status, message, result = call_workflow(api_key='test_key', workspace_name='test_workspace', workflow_id='wf_new', inputs={'input': 'data'}, request_timeout=30, call_chain=call_chain, workflow_version_id=None)

def test_workflow_caller_block_run_with_none_workspace():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test run raises RuntimeError when workspace cannot be resolved.'
    block = WorkflowCallerBlockV1(api_key=None)
    with pytest.raises(RuntimeError) as excinfo:
        _call__bound__arguments = inspect.signature(block.run).bind(workflow_id='test_wf', inputs={}, request_timeout=30, input_definitions={}, output_definitions={})
        _call__bound__arguments.apply_defaults()
        codeflash_return_value = codeflash_wrap(block.run, 'tests.inference.unit_tests.test_run__unit_test_1', None, 'test_workflow_caller_block_run_with_none_workspace', 'run', '2_0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)

def test_workflow_caller_block_run_with_api_error():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test run raises RuntimeError when workflow execution fails.'
    block = WorkflowCallerBlockV1(api_key='test_key')
    with patch.object(block, '_resolve_workspace_name', return_value='test_workspace'):
        with patch('inference.core.workflows.core_steps.composition.workflow_caller.v1.call_workflow') as mock_call:
            mock_call.return_value = (True, 'Workflow execution error', {})
            with pytest.raises(RuntimeError) as excinfo:
                _call__bound__arguments = inspect.signature(block.run).bind(workflow_id='test_wf', inputs={}, request_timeout=30, input_definitions={}, output_definitions={})
                _call__bound__arguments.apply_defaults()
                codeflash_return_value = codeflash_wrap(block.run, 'tests.inference.unit_tests.test_run__unit_test_1', None, 'test_workflow_caller_block_run_with_api_error', 'run', '2_0_1_0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)

def test_build_workflow_inputs_with_empty_dict():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test build_workflow_inputs with empty dictionary.'
    result = build_workflow_inputs({})

def test_build_workflow_inputs_with_none_values():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test build_workflow_inputs preserves None values.'
    inputs = {'key1': None, 'key2': 'value'}
    result = build_workflow_inputs(inputs)

def test_build_workflow_inputs_with_numeric_keys_in_nested_dict():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test build_workflow_inputs with numeric values.'
    inputs = {'int_val': 0, 'float_val': 3.14, 'negative': -42, 'zero_float': 0.0}
    result = build_workflow_inputs(inputs)

def test_deserialize_output_value_no_deserializer_found():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test _deserialize_output_value when no deserializer matches the kind.'
    kind = Kind(name='CustomKind')
    result = _deserialize_output_value(output_name='output1', raw_value={'data': 'test'}, output_kinds=[kind], deserializers={})

def test_deserialize_output_value_deserializer_fails():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test _deserialize_output_value raises error when deserializer fails.'

    def failing_deserializer(name: str, value: Any) -> Any:
        raise ValueError('Deserialization failed')
    kind = Kind(name='BadKind')
    deserializers = {'BadKind': failing_deserializer}
    with pytest.raises(RuntimeError) as excinfo:
        _deserialize_output_value(output_name='output1', raw_value={'data': 'test'}, output_kinds=[kind], deserializers=deserializers)

def test_call_workflow_with_none_api_key():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test call_workflow with None api_key.'
    with patch('inference.core.workflows.core_steps.composition.workflow_caller.v1.execute_workflow_request') as mock_execute:
        mock_execute.return_value = (False, 'Success', {'output': 'value'})
        error_status, message, result = call_workflow(api_key=None, workspace_name='test_workspace', workflow_id='wf1', inputs={}, request_timeout=30, call_chain='', workflow_version_id=None)

def test_call_workflow_with_whitespace_call_chain():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test call_workflow with whitespace-only call chain.'
    with patch('inference.core.workflows.core_steps.composition.workflow_caller.v1.execute_workflow_request') as mock_execute:
        mock_execute.return_value = (False, 'Success', {})
        error_status, message, result = call_workflow(api_key='test_key', workspace_name='test_workspace', workflow_id='wf1', inputs={}, request_timeout=30, call_chain='', workflow_version_id=None)

def test_make_cache_key_with_none_version():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test _make_cache_key explicitly with None version_id.'
    key = _make_cache_key(workflow_id='wf', workflow_version_id=None)

def test_make_cache_key_with_empty_string_workflow_id():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test _make_cache_key with empty string workflow_id.'
    key = _make_cache_key(workflow_id='', workflow_version_id=None)

def test_call_workflow_with_none_call_chain():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test call_workflow with None call_chain parameter.'
    with patch('inference.core.workflows.core_steps.composition.workflow_caller.v1.execute_workflow_request') as mock_execute:
        mock_execute.return_value = (False, 'Success', {})
        error_status, message, result = call_workflow(api_key='test_key', workspace_name='test_workspace', workflow_id='wf1', inputs={}, request_timeout=30, call_chain=None, workflow_version_id=None)

def test_call_workflow_with_multiple_entries_in_chain():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test call_workflow with pre-populated call chain.'
    with patch('inference.core.workflows.core_steps.composition.workflow_caller.v1.execute_workflow_request') as mock_execute:
        mock_execute.return_value = (False, 'Success', {})
        error_status, message, result = call_workflow(api_key='test_key', workspace_name='test_workspace', workflow_id='wf3', inputs={}, request_timeout=30, call_chain='wf1,wf2', workflow_version_id='v1')
        mock_execute.assert_called_once()
        _, kwargs = mock_execute.call_args

def test_resolve_output_kinds_for_run_with_empty_output_definitions():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test _resolve_output_kinds_for_run with empty output_definitions dict.'
    _RESOLVED_WORKFLOW_OUTPUTS.clear()
    result = _resolve_output_kinds_for_run(output_definitions={}, workflow_id='wf', workflow_version_id=None)

def test_deserialize_output_value_with_multiple_kinds_and_working_deserializer():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test _deserialize_output_value tries deserializers in order until one works.'

    def working_deserializer(name: str, value: Any) -> Any:
        return {'deserialized': value}
    kind1 = Kind(name='Kind1')
    kind2 = Kind(name='Kind2')
    deserializers = {'Kind2': working_deserializer}
    result = _deserialize_output_value(output_name='output1', raw_value={'raw': 'data'}, output_kinds=[kind1, kind2], deserializers=deserializers)

def test_deserialize_output_value_mixed_kinds_with_wildcard():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test _deserialize_output_value skips WILDCARD_KIND in deserialization.'

    def deserializer(name: str, value: Any) -> Any:
        return {'result': value}
    kind = Kind(name='TestKind')
    result = _deserialize_output_value(output_name='output1', raw_value={'data': 'test'}, output_kinds=[WILDCARD_KIND, kind], deserializers={'TestKind': deserializer})

def test_build_workflow_inputs_with_large_flat_dict():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test build_workflow_inputs with large flat dictionary (500 entries).'
    inputs = {f'key_{i}': f'value_{i}' for i in range(500)}
    result = build_workflow_inputs(inputs)

def test_build_workflow_inputs_with_large_nested_structure():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test build_workflow_inputs with large nested structures (100 levels).'
    nested = {'level_0': 'value'}
    current = nested
    for i in range(1, 100):
        current[f'level_{i}'] = {}
        current = current[f'level_{i}']
    current['final'] = 'end'
    inputs = {'root': nested}
    result = build_workflow_inputs(inputs)

def test_build_workflow_inputs_with_large_list_values():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test build_workflow_inputs with large list values (1000 elements).'
    inputs = {'large_list': list(range(1000)), 'large_string_list': [f'string_{i}' for i in range(1000)]}
    result = build_workflow_inputs(inputs)

def test_call_workflow_chain_scaling_near_max_depth():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test call_workflow with call chain near maximum depth.'
    chain_entries = [f'wf{i}' for i in range(9)]
    call_chain = ','.join(chain_entries)
    with patch('inference.core.workflows.core_steps.composition.workflow_caller.v1.execute_workflow_request') as mock_execute:
        mock_execute.return_value = (False, 'Success', {})
        error_status, message, result = call_workflow(api_key='test_key', workspace_name='test_workspace', workflow_id='wf_new', inputs={}, request_timeout=30, call_chain=call_chain, workflow_version_id=None)

def test_call_workflow_with_large_inputs_dict():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test call_workflow with large inputs dictionary (100 keys).'
    large_inputs = {f'param_{i}': f'value_{i}' for i in range(100)}
    with patch('inference.core.workflows.core_steps.composition.workflow_caller.v1.execute_workflow_request') as mock_execute:
        mock_execute.return_value = (False, 'Success', {})
        error_status, message, result = call_workflow(api_key='test_key', workspace_name='test_workspace', workflow_id='wf', inputs=large_inputs, request_timeout=30, call_chain='', workflow_version_id=None)
        mock_execute.assert_called_once()

def test_make_cache_key_repeated_calls_performance():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test _make_cache_key performance with repeated calls (1000 iterations).'
    keys = []
    for i in range(1000):
        key = _make_cache_key(workflow_id=f'workflow_{i}', workflow_version_id=f'version_{i}')
        keys.append(key)

def test_deserialize_output_value_with_large_dict_structure():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test _deserialize_output_value with large dictionary (1000 keys).'
    large_dict = {f'key_{i}': f'value_{i}' for i in range(1000)}
    result = _deserialize_output_value(output_name='output', raw_value=large_dict, output_kinds=[WILDCARD_KIND], deserializers={})

def test_build_workflow_inputs_with_many_calls():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test build_workflow_inputs called repeatedly (100 times) with different inputs.'
    for iteration in range(100):
        inputs = {f'key_{j}': f'value_{j}_{iteration}' for j in range(10)}
        result = build_workflow_inputs(inputs)

def test_call_workflow_with_many_circular_checks():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test call_workflow circular detection across 50 iterations.'
    base_chain = 'wf0,wf1,wf2'
    for i in range(3, 50):
        wf_id = f'wf{i}'
        with patch('inference.core.workflows.core_steps.composition.workflow_caller.v1.execute_workflow_request') as mock_execute:
            mock_execute.return_value = (False, 'Success', {})
            error_status, message, result = call_workflow(api_key='test_key', workspace_name='test_workspace', workflow_id=wf_id, inputs={}, request_timeout=30, call_chain=base_chain, workflow_version_id=None)

def test_make_cache_key_consistency_across_calls():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test _make_cache_key produces consistent keys across 1000 identical calls.'
    keys = [_make_cache_key(workflow_id='same_workflow', workflow_version_id='v1') for _ in range(1000)]

def test_workflow_caller_block_resolve_workspace_name_with_cache():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test _resolve_workspace_name caches result and reuses it.'
    block = WorkflowCallerBlockV1(api_key='test_key')
    with patch('inference.core.workflows.core_steps.composition.workflow_caller.v1.get_roboflow_workspace') as mock_get:
        mock_get.return_value = 'test_workspace'
        ws1 = block._resolve_workspace_name()
        ws2 = block._resolve_workspace_name()

def test_build_workflow_inputs_preserves_complex_types():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test build_workflow_inputs preserves complex nested types over 100 iterations.'
    for _ in range(100):
        inputs = {'complex': {'nested': {'list': [1, 2, {'inner': 'value'}], 'dict': {'key': 'value'}}}}
        result = build_workflow_inputs(inputs)

def test_call_workflow_chain_with_trailing_comma():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test call_workflow handles call_chain with trailing comma gracefully.'
    with patch('inference.core.workflows.core_steps.composition.workflow_caller.v1.execute_workflow_request') as mock_execute:
        mock_execute.return_value = (False, 'Success', {})
        error_status, message, result = call_workflow(api_key='test_key', workspace_name='test_workspace', workflow_id='wf_new', inputs={}, request_timeout=30, call_chain='wf1,wf2,', workflow_version_id=None)

def test_deserialize_output_value_with_empty_kinds_list():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test _deserialize_output_value with empty kinds list.'
    result = _deserialize_output_value(output_name='output', raw_value={'data': 'test'}, output_kinds=[], deserializers={})

def test_build_workflow_inputs_with_boolean_values():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    'Test build_workflow_inputs preserves boolean values correctly.'
    inputs = {'true_val': True, 'false_val': False, 'mixed': [True, False, True]}
    result = build_workflow_inputs(inputs)

def test_workflow_caller_block_run_fallback_to_result_generic():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    "Test run falls back to generic 'result' key when output_definitions is None."
    block = WorkflowCallerBlockV1(api_key='test_key')
    with patch.object(block, '_resolve_workspace_name', return_value='test_workspace'):
        with patch('inference.core.workflows.core_steps.composition.workflow_caller.v1.call_workflow') as mock_call:
            mock_call.return_value = (False, 'Success', {'output1': 'value1'})
            with patch('inference.core.workflows.core_steps.composition.workflow_caller.v1._resolve_output_kinds_for_run', return_value=None):
                _call__bound__arguments = inspect.signature(block.run).bind(workflow_id='test_wf', inputs={}, request_timeout=30, input_definitions={}, output_definitions={})
                _call__bound__arguments.apply_defaults()
                codeflash_return_value = codeflash_wrap(block.run, 'tests.inference.unit_tests.test_run__unit_test_1', None, 'test_workflow_caller_block_run_fallback_to_result_generic', 'run', '2_0_1_0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
                codeflash_output = codeflash_return_value
                result = codeflash_output