from __future__ import annotations

import gc
import os
import threading
import time
from contextlib import contextmanager
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"])
    "Test that _dispose_model_lock removes an existing lock for a model_id."
    manager = ModelManager(ModelRegistry())
    manager._models_state_locks["model_a"] = threading.Lock()
    codeflash_return_value = codeflash_wrap(
        manager._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_1",
        None,
        "test_dispose_existing_model_lock_removes_lock",
        "_dispose_model_lock",
        "3",
        codeflash_loop_index,
        "model_a",
    )


def test_dispose_nonexistent_model_lock_does_nothing():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    "Test that disposing a lock for a non-existent model_id does nothing."
    manager = ModelManager(ModelRegistry())
    manager._models_state_locks["model_b"] = threading.Lock()
    before = dict(manager._models_state_locks)
    codeflash_return_value = codeflash_wrap(
        manager._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_1",
        None,
        "test_dispose_nonexistent_model_lock_does_nothing",
        "_dispose_model_lock",
        "4",
        codeflash_loop_index,
        "model_x",
    )


def test_dispose_model_lock_returns_none_when_lock_missing():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    "Test that _dispose_model_lock returns None if the lock is missing."
    manager = ModelManager(ModelRegistry())
    codeflash_return_value = codeflash_wrap(
        manager._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_1",
        None,
        "test_dispose_model_lock_returns_none_when_lock_missing",
        "_dispose_model_lock",
        "2",
        codeflash_loop_index,
        "model_c",
    )
    codeflash_output = codeflash_return_value
    result = codeflash_output


def test_dispose_model_lock_with_empty_locks_dict():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    "Test disposing when _models_state_locks is empty."
    manager = ModelManager(ModelRegistry())
    codeflash_return_value = codeflash_wrap(
        manager._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_1",
        None,
        "test_dispose_model_lock_with_empty_locks_dict",
        "_dispose_model_lock",
        "2",
        codeflash_loop_index,
        "model_z",
    )
    codeflash_output = codeflash_return_value
    result = codeflash_output


def test_dispose_model_lock_with_non_string_model_id():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    "Test disposing with a non-string model_id (should work for any hashable key)."
    manager = ModelManager(ModelRegistry())
    key = 12345
    manager._models_state_locks[key] = threading.Lock()
    codeflash_return_value = codeflash_wrap(
        manager._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_1",
        None,
        "test_dispose_model_lock_with_non_string_model_id",
        "_dispose_model_lock",
        "4",
        codeflash_loop_index,
        key,
    )


def test_dispose_model_lock_with_special_characters():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    "Test disposing with a model_id containing special characters."
    manager = ModelManager(ModelRegistry())
    special_id = "model_!@#$%^&*()"
    manager._models_state_locks[special_id] = threading.Lock()
    codeflash_return_value = codeflash_wrap(
        manager._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_1",
        None,
        "test_dispose_model_lock_with_special_characters",
        "_dispose_model_lock",
        "4",
        codeflash_loop_index,
        special_id,
    )


def test_dispose_model_lock_lock_acquisition_failure():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    "Test that if the state lock cannot be acquired, an exception is raised."
    manager = ModelManager(ModelRegistry())
    manager._models_state_locks["model_fail"] = threading.Lock()

    def lock_and_sleep(lock):
        lock.acquire()
        time.sleep(MODEL_LOCK_ACQUIRE_TIMEOUT + 0.2)
        lock.release()

    t = threading.Thread(target=lock_and_sleep, args=(manager._state_lock,))
    t.start()
    time.sleep(0.02)
    with pytest.raises(ModelManagerLockAcquisitionError):
        codeflash_return_value = codeflash_wrap(
            manager._dispose_model_lock,
            "tests.inference.unit_tests.test__dispose_model_lock__unit_test_1",
            None,
            "test_dispose_model_lock_lock_acquisition_failure",
            "_dispose_model_lock",
            "7_0",
            codeflash_loop_index,
            "model_fail",
        )
    t.join()


def test_dispose_model_lock_with_multiple_calls():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    "Test that repeated calls for the same model_id are idempotent."
    manager = ModelManager(ModelRegistry())
    manager._models_state_locks["model_dupe"] = threading.Lock()
    codeflash_return_value = codeflash_wrap(
        manager._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_1",
        None,
        "test_dispose_model_lock_with_multiple_calls",
        "_dispose_model_lock",
        "3",
        codeflash_loop_index,
        "model_dupe",
    )
    codeflash_return_value = codeflash_wrap(
        manager._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_1",
        None,
        "test_dispose_model_lock_with_multiple_calls",
        "_dispose_model_lock",
        "4",
        codeflash_loop_index,
        "model_dupe",
    )


def test_dispose_model_lock_with_none_model_id():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    "Test disposing with None as model_id."
    manager = ModelManager(ModelRegistry())
    manager._models_state_locks[None] = threading.Lock()
    codeflash_return_value = codeflash_wrap(
        manager._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_1",
        None,
        "test_dispose_model_lock_with_none_model_id",
        "_dispose_model_lock",
        "3",
        codeflash_loop_index,
        None,
    )


def test_dispose_model_lock_with_empty_string_model_id():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    "Test disposing with empty string as model_id."
    manager = ModelManager(ModelRegistry())
    manager._models_state_locks[""] = threading.Lock()
    codeflash_return_value = codeflash_wrap(
        manager._dispose_model_lock,
        "tests.inference.unit_tests.test__dispose_model_lock__unit_test_1",
        None,
        "test_dispose_model_lock_with_empty_string_model_id",
        "_dispose_model_lock",
        "3",
        codeflash_loop_index,
        "",
    )


def test_dispose_model_lock_large_scale_removal():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    "Test disposing locks in a large manager with many model_ids."
    manager = ModelManager(ModelRegistry())
    num_models = 500
    for i in range(num_models):
        manager._models_state_locks[f"model_{i}"] = threading.Lock()
    for i in range(0, num_models, 2):
        codeflash_return_value = codeflash_wrap(
            manager._dispose_model_lock,
            "tests.inference.unit_tests.test__dispose_model_lock__unit_test_1",
            None,
            "test_dispose_model_lock_large_scale_removal",
            "_dispose_model_lock",
            "4_0",
            codeflash_loop_index,
            f"model_{i}",
        )
    for i in range(num_models):
        if i % 2 == 0:
            pass
        else:
            pass


def test_dispose_model_lock_large_scale_idempotency():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    "Test that disposing all locks twice does not raise and is idempotent."
    manager = ModelManager(ModelRegistry())
    num_models = 300
    for i in range(num_models):
        manager._models_state_locks[f"model_{i}"] = threading.Lock()
    for i in range(num_models):
        codeflash_return_value = codeflash_wrap(
            manager._dispose_model_lock,
            "tests.inference.unit_tests.test__dispose_model_lock__unit_test_1",
            None,
            "test_dispose_model_lock_large_scale_idempotency",
            "_dispose_model_lock",
            "4_0",
            codeflash_loop_index,
            f"model_{i}",
        )
    for i in range(num_models):
        codeflash_return_value = codeflash_wrap(
            manager._dispose_model_lock,
            "tests.inference.unit_tests.test__dispose_model_lock__unit_test_1",
            None,
            "test_dispose_model_lock_large_scale_idempotency",
            "_dispose_model_lock",
            "5_0",
            codeflash_loop_index,
            f"model_{i}",
        )


def test_dispose_model_lock_large_scale_performance():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    "Test performance: disposing locks in a large manager should not be slow."
    manager = ModelManager(ModelRegistry())
    num_models = 800
    for i in range(num_models):
        manager._models_state_locks[f"model_{i}"] = threading.Lock()
    start = time.time()
    for i in range(num_models):
        codeflash_return_value = codeflash_wrap(
            manager._dispose_model_lock,
            "tests.inference.unit_tests.test__dispose_model_lock__unit_test_1",
            None,
            "test_dispose_model_lock_large_scale_performance",
            "_dispose_model_lock",
            "5_0",
            codeflash_loop_index,
            f"model_{i}",
        )
    duration = time.time() - start


def test_dispose_model_lock_large_scale_nonexistent_ids():
    codeflash_loop_index = int(os.environ["CODEFLASH_LOOP_INDEX"])
    "Test disposing locks for many non-existent model_ids in a large manager."
    manager = ModelManager(ModelRegistry())
    num_models = 100
    for i in range(num_models):
        manager._models_state_locks[f"model_{i}"] = threading.Lock()
    for i in range(num_models, num_models + 100):
        codeflash_return_value = codeflash_wrap(
            manager._dispose_model_lock,
            "tests.inference.unit_tests.test__dispose_model_lock__unit_test_1",
            None,
            "test_dispose_model_lock_large_scale_nonexistent_ids",
            "_dispose_model_lock",
            "4_0",
            codeflash_loop_index,
            f"model_{i}",
        )
    for i in range(num_models):
        pass
