from __future__ import annotations

import gc
import os
import threading
import time
from contextlib import contextmanager
from threading import Lock
from typing import Any, Callable, Dict, Generator, Optional

import pytest
from inference.core.managers.base import ModelManager

def codeflash_wrap(
    codeflash_wrapped: Callable[..., Any],
    codeflash_test_module_name: str,
    codeflash_test_class_name: Optional[str],
    codeflash_test_name: str,
    codeflash_function_name: str,
    codeflash_line_id: str,
    codeflash_loop_index: int,
    *args: Any,
    **kwargs: Any,
) -> str:
    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}"
    exception = None
    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}######$!")
    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

class ModelManagerLockAcquisitionError(Exception):
    pass


class Model:
    pass


class ModelRegistry:
    pass


def test_dispose_existing_model_lock_removes_lock():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    mm = ModelManager(ModelRegistry())
    mm._models_state_locks["model_a"] = Lock()
    codeflash_return_value = codeflash_wrap(
        mm._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_0",
        None,
        "test_dispose_existing_model_lock_removes_lock",
        "_dispose_model_lock",
        "2",
        codeflash_loop_index,
        "model_a",
    )


def test_dispose_nonexistent_model_lock_does_nothing():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    mm = ModelManager(ModelRegistry())
    codeflash_return_value = codeflash_wrap(
        mm._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_0",
        None,
        "test_dispose_nonexistent_model_lock_does_nothing",
        "_dispose_model_lock",
        "1",
        codeflash_loop_index,
        "model_x",
    )
    codeflash_output = codeflash_return_value
    result = codeflash_output


def test_dispose_model_lock_with_multiple_locks_removes_only_target():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    mm = ModelManager(ModelRegistry())
    mm._models_state_locks["model_a"] = Lock()
    mm._models_state_locks["model_b"] = Lock()
    mm._models_state_locks["model_c"] = Lock()
    codeflash_return_value = codeflash_wrap(
        mm._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_0",
        None,
        "test_dispose_model_lock_with_multiple_locks_removes_only_target",
        "_dispose_model_lock",
        "4",
        codeflash_loop_index,
        "model_b",
    )


def test_dispose_model_lock_returns_none_when_lock_removed():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    mm = ModelManager(ModelRegistry())
    mm._models_state_locks["model_a"] = Lock()
    codeflash_return_value = codeflash_wrap(
        mm._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_0",
        None,
        "test_dispose_model_lock_returns_none_when_lock_removed",
        "_dispose_model_lock",
        "2",
        codeflash_loop_index,
        "model_a",
    )
    codeflash_output = codeflash_return_value
    result = codeflash_output


def test_dispose_model_lock_with_empty_dict():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    mm = ModelManager(ModelRegistry())
    codeflash_return_value = codeflash_wrap(
        mm._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_0",
        None,
        "test_dispose_model_lock_with_empty_dict",
        "_dispose_model_lock",
        "1",
        codeflash_loop_index,
        "any_model",
    )
    codeflash_output = codeflash_return_value
    result = codeflash_output


def test_dispose_model_lock_with_model_id_not_string():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    mm = ModelManager(ModelRegistry())
    mm._models_state_locks[123] = Lock()
    codeflash_return_value = codeflash_wrap(
        mm._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_0",
        None,
        "test_dispose_model_lock_with_model_id_not_string",
        "_dispose_model_lock",
        "2",
        codeflash_loop_index,
        123,
    )


def test_dispose_model_lock_with_special_characters_in_model_id():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    mm = ModelManager(ModelRegistry())
    mm._models_state_locks["!@#$_model"] = Lock()
    codeflash_return_value = codeflash_wrap(
        mm._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_0",
        None,
        "test_dispose_model_lock_with_special_characters_in_model_id",
        "_dispose_model_lock",
        "2",
        codeflash_loop_index,
        "!@#$_model",
    )


def test_dispose_model_lock_when_lock_cannot_be_acquired():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    mm = ModelManager(ModelRegistry())
    mm._models_state_locks["model_a"] = Lock()
    mm._state_lock.acquire()
    try:
        with pytest.raises(ModelManagerLockAcquisitionError):
            codeflash_return_value = codeflash_wrap(
                mm._dispose_model_lock,
                "tests.inference.unit_tests.test__dispose_model_lock__unit_test_0",
                None,
                "test_dispose_model_lock_when_lock_cannot_be_acquired",
                "_dispose_model_lock",
                "3_0_0",
                codeflash_loop_index,
                "model_a",
            )
    finally:
        mm._state_lock.release()


def test_dispose_model_lock_with_none_model_id():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    mm = ModelManager(ModelRegistry())
    mm._models_state_locks[None] = Lock()
    codeflash_return_value = codeflash_wrap(
        mm._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_0",
        None,
        "test_dispose_model_lock_with_none_model_id",
        "_dispose_model_lock",
        "2",
        codeflash_loop_index,
        None,
    )


def test_dispose_model_lock_with_large_string_model_id():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    long_id = "model_" + "x" * 500
    mm = ModelManager(ModelRegistry())
    mm._models_state_locks[long_id] = Lock()
    codeflash_return_value = codeflash_wrap(
        mm._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_0",
        None,
        "test_dispose_model_lock_with_large_string_model_id",
        "_dispose_model_lock",
        "3",
        codeflash_loop_index,
        long_id,
    )


def test_dispose_model_lock_with_model_id_collision():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    mm = ModelManager(ModelRegistry())
    mm._models_state_locks["model"] = Lock()
    mm._models_state_locks["model "] = Lock()
    codeflash_return_value = codeflash_wrap(
        mm._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_0",
        None,
        "test_dispose_model_lock_with_model_id_collision",
        "_dispose_model_lock",
        "3",
        codeflash_loop_index,
        "model ",
    )


def test_dispose_model_lock_large_scale_removal():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    mm = ModelManager(ModelRegistry())
    for i in range(1000):
        mm._models_state_locks[f"model_{i}"] = Lock()
    for i in range(0, 1000, 100):
        codeflash_return_value = codeflash_wrap(
            mm._dispose_model_lock,
            "tests.inference.unit_tests.test__dispose_model_lock__unit_test_0",
            None,
            "test_dispose_model_lock_large_scale_removal",
            "_dispose_model_lock",
            "2_0",
            codeflash_loop_index,
            f"model_{i}",
        )
    for i in range(0, 1000, 100):
        pass
    for i in range(1, 1000):
        if i % 100 != 0:
            pass


def test_dispose_model_lock_performance_under_load():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    mm = ModelManager(ModelRegistry())
    for i in range(500):
        mm._models_state_locks[f"model_{i}"] = Lock()
    start = time.time()
    for i in range(500):
        codeflash_return_value = codeflash_wrap(
            mm._dispose_model_lock,
            "tests.inference.unit_tests.test__dispose_model_lock__unit_test_0",
            None,
            "test_dispose_model_lock_performance_under_load",
            "_dispose_model_lock",
            "3_0",
            codeflash_loop_index,
            f"model_{i}",
        )
    duration = time.time() - start


def test_dispose_model_lock_thread_safety_under_contention():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    mm = ModelManager(ModelRegistry())
    mm._models_state_locks["model_a"] = Lock()

    def hold_lock(lock, duration):
        lock.acquire()
        time.sleep(duration)
        lock.release()

    t = threading.Thread(target=hold_lock, args=(mm._state_lock, 0.2))
    t.start()
    time.sleep(0.05)
    with pytest.raises(ModelManagerLockAcquisitionError):
        codeflash_return_value = codeflash_wrap(
            mm._dispose_model_lock,
            "tests.inference.unit_tests.test__dispose_model_lock__unit_test_0",
            None,
            "test_dispose_model_lock_thread_safety_under_contention",
            "_dispose_model_lock",
            "6_0",
            codeflash_loop_index,
            "model_a",
        )
    t.join()
    codeflash_return_value = codeflash_wrap(
        mm._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_0",
        None,
        "test_dispose_model_lock_thread_safety_under_contention",
        "_dispose_model_lock",
        "8",
        codeflash_loop_index,
        "model_a",
    )


def test_dispose_model_lock_removal_does_not_affect_other_manager_instances():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    mm1 = ModelManager(ModelRegistry())
    mm2 = ModelManager(ModelRegistry())
    mm1._models_state_locks["model_a"] = Lock()
    mm2._models_state_locks["model_a"] = Lock()
    codeflash_return_value = codeflash_wrap(
        mm1._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_0",
        None,
        "test_dispose_model_lock_removal_does_not_affect_other_manager_instances",
        "_dispose_model_lock",
        "4",
        codeflash_loop_index,
        "model_a",
    )


def test_dispose_model_lock_large_scale_with_varied_keys():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    mm = ModelManager(ModelRegistry())
    for i in range(500):
        mm._models_state_locks[i] = Lock()
    for i in range(500):
        mm._models_state_locks[f"model_{i}"] = Lock()
    for i in range(500):
        codeflash_return_value = codeflash_wrap(
            mm._dispose_model_lock,
            "tests.inference.unit_tests.test__dispose_model_lock__unit_test_0",
            None,
            "test_dispose_model_lock_large_scale_with_varied_keys",
            "_dispose_model_lock",
            "3_0",
            codeflash_loop_index,
            i,
        )
    for i in range(500):
        pass
