from __future__ import annotations

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

import dill as pickle
import pytest
from inference.core.cache.air_gapped import _is_model_cached, _slugify_model_id
from inference.core.env import MODEL_CACHE_DIR


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
air_gapped = importlib.import_module('inference.core.cache.air_gapped')

def test_traditional_layout_detects_cache_basic(tmp_path):
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    air_gapped.MODEL_CACHE_DIR = str(tmp_path)
    model_dir = tmp_path / 'modelA'
    model_dir.mkdir(parents=True, exist_ok=True)
    (model_dir / 'weights.bin').write_bytes(b'binaryweights')
    _call__bound__arguments = inspect.signature(_is_model_cached).bind('modelA')
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_is_model_cached, 'tests.inference.unit_tests.test__is_model_cached__unit_test_0', None, 'test_traditional_layout_detects_cache_basic', '_is_model_cached', '4', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    _call__bound__arguments = inspect.signature(_is_model_cached).bind('no-such-model')
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_is_model_cached, 'tests.inference.unit_tests.test__is_model_cached__unit_test_0', None, 'test_traditional_layout_detects_cache_basic', '_is_model_cached', '5', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value

def test_inference_models_layout_detects_cache_with_subdirectory(tmp_path):
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    air_gapped.MODEL_CACHE_DIR = str(tmp_path)
    model_id = 'My Model@@@/v1'
    slug = _slugify_model_id(model_id)
    slug_dir = tmp_path / 'models-cache' / slug
    (slug_dir / 'subdir').mkdir(parents=True, exist_ok=True)
    (slug_dir / 'subdir' / 'config.json').write_text('{"ok": true}')
    _call__bound__arguments = inspect.signature(_is_model_cached).bind(model_id)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_is_model_cached, 'tests.inference.unit_tests.test__is_model_cached__unit_test_0', None, 'test_inference_models_layout_detects_cache_with_subdirectory', '_is_model_cached', '6', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value

def test_empty_directories_do_not_count_as_cached(tmp_path):
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    air_gapped.MODEL_CACHE_DIR = str(tmp_path)
    (tmp_path / 'empty_model').mkdir(parents=True, exist_ok=True)
    empty_slug = _slugify_model_id('++++')
    (tmp_path / 'models-cache' / empty_slug).mkdir(parents=True, exist_ok=True)
    _call__bound__arguments = inspect.signature(_is_model_cached).bind('empty_model')
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_is_model_cached, 'tests.inference.unit_tests.test__is_model_cached__unit_test_0', None, 'test_empty_directories_do_not_count_as_cached', '_is_model_cached', '4', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    _call__bound__arguments = inspect.signature(_is_model_cached).bind('++++')
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_is_model_cached, 'tests.inference.unit_tests.test__is_model_cached__unit_test_0', None, 'test_empty_directories_do_not_count_as_cached', '_is_model_cached', '5', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value

def test_slugify_edge_cases_and_truncation_behavior(tmp_path):
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    air_gapped.MODEL_CACHE_DIR = str(tmp_path)
    long_model_id = 'a' * 100
    long_slug = _slugify_model_id(long_model_id)
    (tmp_path / 'models-cache' / long_slug).mkdir(parents=True, exist_ok=True)
    (tmp_path / 'models-cache' / long_slug / 'file.bin').write_bytes(b'x')
    _call__bound__arguments = inspect.signature(_is_model_cached).bind(long_model_id)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_is_model_cached, 'tests.inference.unit_tests.test__is_model_cached__unit_test_0', None, 'test_slugify_edge_cases_and_truncation_behavior', '_is_model_cached', '5', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    special_id = '@@@'
    special_slug = _slugify_model_id(special_id)
    (tmp_path / 'models-cache' / special_slug).mkdir(parents=True, exist_ok=True)
    (tmp_path / 'models-cache' / special_slug / 'f').write_text('1')
    _call__bound__arguments = inspect.signature(_is_model_cached).bind(special_id)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_is_model_cached, 'tests.inference.unit_tests.test__is_model_cached__unit_test_0', None, 'test_slugify_edge_cases_and_truncation_behavior', '_is_model_cached', '10', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value

def test_invalid_type_raises_type_error(tmp_path):
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    air_gapped.MODEL_CACHE_DIR = str(tmp_path)
    with pytest.raises(TypeError):
        _call__bound__arguments = inspect.signature(_is_model_cached).bind(None)
        _call__bound__arguments.apply_defaults()
        codeflash_return_value = codeflash_wrap(_is_model_cached, 'tests.inference.unit_tests.test__is_model_cached__unit_test_0', None, 'test_invalid_type_raises_type_error', '_is_model_cached', '1_0', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)

def test_large_scale_many_model_directories(tmp_path):
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    air_gapped.MODEL_CACHE_DIR = str(tmp_path)
    n = 1000
    base = tmp_path
    for i in range(n):
        name = f'm{i:04d}'
        d = base / name
        d.mkdir(parents=True, exist_ok=True)
        (d / 'f.txt').write_text('x')
    _call__bound__arguments = inspect.signature(_is_model_cached).bind('m0000')
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_is_model_cached, 'tests.inference.unit_tests.test__is_model_cached__unit_test_0', None, 'test_large_scale_many_model_directories', '_is_model_cached', '4', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    _call__bound__arguments = inspect.signature(_is_model_cached).bind(f'm{n - 1:04d}')
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_is_model_cached, 'tests.inference.unit_tests.test__is_model_cached__unit_test_0', None, 'test_large_scale_many_model_directories', '_is_model_cached', '5', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    _call__bound__arguments = inspect.signature(_is_model_cached).bind('m0500')
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_is_model_cached, 'tests.inference.unit_tests.test__is_model_cached__unit_test_0', None, 'test_large_scale_many_model_directories', '_is_model_cached', '6', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value
    _call__bound__arguments = inspect.signature(_is_model_cached).bind('m1001')
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_is_model_cached, 'tests.inference.unit_tests.test__is_model_cached__unit_test_0', None, 'test_large_scale_many_model_directories', '_is_model_cached', '7', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value

def test_models_cache_single_directory_with_many_entries(tmp_path):
    codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
    air_gapped.MODEL_CACHE_DIR = str(tmp_path)
    model_id = 'heavy-model'
    slug = _slugify_model_id(model_id)
    slug_dir = tmp_path / 'models-cache' / slug
    slug_dir.mkdir(parents=True, exist_ok=True)
    for i in range(1000):
        (slug_dir / f'file_{i:04d}.dat').write_text('data')
    _call__bound__arguments = inspect.signature(_is_model_cached).bind(model_id)
    _call__bound__arguments.apply_defaults()
    codeflash_return_value = codeflash_wrap(_is_model_cached, 'tests.inference.unit_tests.test__is_model_cached__unit_test_0', None, 'test_models_cache_single_directory_with_many_entries', '_is_model_cached', '6', codeflash_loop_index, *_call__bound__arguments.args, **_call__bound__arguments.kwargs)
    codeflash_output = codeflash_return_value