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.composition.workflow_caller.v1 import (
    WORKFLOW_CALLER_BLOCK_TYPE, _check_workflow_for_circular_references,
    _extract_workflow_caller_ids_from_spec)
from inference.core.workflows.errors import ExecutionGraphStructureError


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_extract_empty_spec_returns_empty():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    spec = {}
    result = _extract_workflow_caller_ids_from_spec(spec=spec)

def test_extract_ignores_non_workflow_caller_steps():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    spec = {'steps': [{'type': 'some_other_block', 'workflow_id': 'wf'}]}
    result = _extract_workflow_caller_ids_from_spec(spec=spec)

def test_extract_literal_id_and_version_and_variable_version():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    spec = {'steps': [{'type': WORKFLOW_CALLER_BLOCK_TYPE, 'workflow_id': 'my_workflow', 'workflow_version_id': 'v1'}]}
    result = _extract_workflow_caller_ids_from_spec(spec=spec)

def test_extract_ignores_selector_ids_and_non_string_ids():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    spec = {'steps': [{'type': WORKFLOW_CALLER_BLOCK_TYPE, 'workflow_id': '$some_selector', 'workflow_version_id': 'v1'}, {'type': WORKFLOW_CALLER_BLOCK_TYPE, 'workflow_id': 12345, 'workflow_version_id': 'v2'}, {'type': WORKFLOW_CALLER_BLOCK_TYPE, 'workflow_id': 'valid_workflow', 'workflow_version_id': '$var_version'}]}
    result = _extract_workflow_caller_ids_from_spec(spec=spec)

def test_extract_version_with_dollar_becomes_none():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    spec = {'steps': [{'type': WORKFLOW_CALLER_BLOCK_TYPE, 'workflow_id': 'wf', 'workflow_version_id': '$some_selector'}]}
    result = _extract_workflow_caller_ids_from_spec(spec=spec)

def test_check_no_cycle_prefetched_spec_returns_none_for_non_nested():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    prefetched_spec = {'steps': [{'type': 'something_else', 'foo': 'bar'}, {'type': 'another_block', 'x': 'y'}]}
    _call__bound__arguments = inspect.signature(_check_workflow_for_circular_references).bind(api_key=None, workspace_name='any', target_workflow_id='top_workflow', visited=set(), prefetched_spec=prefetched_spec)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_check_workflow_for_circular_references, 'tests.inference.unit_tests.test__check_workflow_for_circular_references__unit_test_0', None, 'test_check_no_cycle_prefetched_spec_returns_none_for_non_nested', '_check_workflow_for_circular_references', '1', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    result = codeflash_output

def test_check_raises_on_direct_cycle_when_visited_contains_target():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    visited = {'A', 'B', 'C'}
    with pytest.raises(ExecutionGraphStructureError) as excinfo:
        _call__bound__arguments = inspect.signature(_check_workflow_for_circular_references).bind(api_key=None, workspace_name='ws', target_workflow_id='B', visited=visited, prefetched_spec={'steps': []})
        _call__bound__arguments.apply_defaults()
        codeflash_return_value = codeflash_wrap(_check_workflow_for_circular_references, 'tests.inference.unit_tests.test__check_workflow_for_circular_references__unit_test_0', None, 'test_check_raises_on_direct_cycle_when_visited_contains_target', '_check_workflow_for_circular_references', '1_0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    message = str(excinfo.value)

def test_extract_large_number_of_steps_performance_and_correctness():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    num_steps = 1000
    steps = []
    expected = []
    for i in range(num_steps):
        if i % 2 == 0:
            wf_id = f'wf_{i}'
            version = f'v_{i}'
            steps.append({'type': WORKFLOW_CALLER_BLOCK_TYPE, 'workflow_id': wf_id, 'workflow_version_id': version})
            expected.append((wf_id, version))
        else:
            steps.append({'type': 'unrelated_block', 'index': i})
    spec = {'steps': steps}
    result = _extract_workflow_caller_ids_from_spec(spec=spec)

def test_extract_with_mixed_types_and_edge_values():
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    spec = {'steps': [{}, {'type': WORKFLOW_CALLER_BLOCK_TYPE, 'workflow_id': ''}, {'type': WORKFLOW_CALLER_BLOCK_TYPE, 'workflow_id': 'wf_ok', 'workflow_version_id': None}, {'type': WORKFLOW_CALLER_BLOCK_TYPE, 'workflow_id': 'wf_strange', 'workflow_version_id': 123}]}
    result = _extract_workflow_caller_ids_from_spec(spec=spec)