import os
import threading

from torch._inductor.kernel.vendored_templates.flydsl.kernels import (
    infer_has_k_tail,
    make_gemm_param_and_validate,
)
from torch._inductor.kernel.vendored_templates.flydsl.kernels.gemm_gfx950 import (
    {% if IS_MXFP %}gemm_mxfp_gfx950{% else %}gemm_gfx950{% endif %} as _kernel,
)
from torch._inductor.runtime.flydsl_cache import (
    configure_flydsl_cache_dir,
    run_cached_flydsl,
    temporary_env,
)

{{gen_defines()}}


_gemm_param = None
_gemm_param_lock = threading.Lock()


def _inductor_tensor_arg(tensor):
    return flyc.from_torch_tensor(tensor).mark_layout_dynamic()


{% if IS_MXFP and HAS_BIAS %}
{{def_kernel("mat1", "mat2", "scale_a", "scale_b", "bias")}}
{% elif IS_MXFP %}
{{def_kernel("mat1", "mat2", "scale_a", "scale_b")}}
{% else %}
{{def_kernel("mat1", "mat2")}}
{% endif %}
    output = {{get_output()}}
{% if IS_MXFP %}
    mat1 = mat1.view(torch.uint8)
    mat2 = mat2.view(torch.uint8)
    scale_a = scale_a.view(torch.uint8)
    scale_b = scale_b.view(torch.uint8)
{% endif %}

    global _gemm_param
    param = _gemm_param
    if param is None:
        with _gemm_param_lock:
            param = _gemm_param
            if param is None:
                has_k_tail = infer_has_k_tail(GEMM_K, TILE_K, STAGES, USE_HALF_TILE_INTERLEAVED)
                param = make_gemm_param_and_validate(
                    GEMM_M,
                    GEMM_N,
                    GEMM_K,
                    {
                        "dtype_id": GEMM_DTYPE_ID,
{% if IS_MXFP %}
                        "out_dtype_id": OUT_DTYPE_ID,
{% endif %}
                        "tile_m": TILE_M,
                        "tile_n": TILE_N,
                        "tile_k": TILE_K,
                        "stages": STAGES,
                        "m_waves": M_WAVES,
                        "n_waves": N_WAVES,
                        "group_m": GROUP_M,
                        "use_half_tile_interleaved": USE_HALF_TILE_INTERLEAVED,
                        "a_is_transposed": A_IS_TRANSPOSED,
                        "b_is_transposed": B_IS_TRANSPOSED,
                        "has_bias": {% if IS_MXFP and HAS_BIAS %}True{% else %}False{% endif %},
                        "has_k_tail": has_k_tail,
                    },
                )
                if param is None:
                    raise RuntimeError(
                        f"unsupported FlyDSL GEMM shape/config: M={GEMM_M}, N={GEMM_N}, "
                        f"K={GEMM_K}, tile=({TILE_M}, {TILE_N}, {TILE_K}), stages={STAGES}"
                    )
                _gemm_param = param
    configure_flydsl_cache_dir()
    tensor_args = (
        output,
        mat1,
        mat2{% if IS_MXFP %},
        scale_a,
        scale_b,
        {% if HAS_BIAS %}bias{% else %}output{% endif %}{% endif %}
    )
    compile_args = tuple(_inductor_tensor_arg(arg) for arg in tensor_args) + (
        param,
        stream,
    )
    flydsl_compile_only = os.environ.get("FLYDSL_COMPILE_ONLY") == "1"
    compile_only = os.environ.get("COMPILE_ONLY", "").lower() in (
        "1", "true", "yes", "on"
    )
    if compile_only != flydsl_compile_only:
        raise RuntimeError(
            "COMPILE_ONLY and FLYDSL_COMPILE_ONLY must only be enabled together "
            "by the FlyDSL precompile path"
        )
    if flydsl_compile_only:
        flyc.compile(_kernel, *compile_args)
    else:
        run_cached_flydsl(
            _kernel,
            *compile_args,
            constexpr_param=param,
            compiler=flyc.compile,
            dispatch_args=(*tensor_args, param, stream),
        )
    return output


def {{kernel_name}}_precompile(
    precompile_shapes,
    precompile_strides,
    precompile_dtypes,
    device_index=0,
    device_capability=None,
    flydsl_gpu_arch=None,
):
    """Warm FlyDSL's disk cache using metadata-only fake tensors."""

    env_updates = {"COMPILE_ONLY": "1", "FLYDSL_COMPILE_ONLY": "1"}
    if flydsl_gpu_arch is not None:
        env_updates["FLYDSL_GPU_ARCH"] = flydsl_gpu_arch

    with temporary_env(env_updates):
        from torch._subclasses.fake_tensor import FakeTensorMode

        with FakeTensorMode():

            def _fake_proxy(name):
                return torch.empty_strided(
                    tuple(precompile_shapes[name]),
                    tuple(precompile_strides[name]),
                    dtype=getattr(torch, precompile_dtypes[name]),
                    device="cpu",
                )

            input_names = ("mat1", "mat2"{% if IS_MXFP %}, "scale_a", "scale_b"{% if HAS_BIAS %}, "bias"{% endif %}{% endif %})
            args = tuple(_fake_proxy(name) for name in input_names) + (
                _fake_proxy("output"),
            )
            {{kernel_name}}_main(*args, stream=0)
