import torch
from torch._inductor.codegen.rocm.rocm_template import ROCmTemplate
from torch._inductor.ir import IRNode
from torch._inductor.utils import IndentedBuffer


class CKTileTemplate(ROCmTemplate):
    """
    Base class for generating CK templates, has common, i.e. non-gemm-specific, code generation logic
    """

    _TORCH_DTYPE_TO_CK = {
        torch.float32: "F32",
        torch.float64: "F64",
        torch.float16: "F16",
        torch.bfloat16: "BF16",
        torch.int32: "I32",
        torch.int8: "I8",
        torch.float8_e4m3fnuz: "F8",  # gfx94
        torch.float8_e4m3fn: "F8",  # gfx95
        torch.float8_e5m2fnuz: "BF8",  # gfx94
        torch.float8_e5m2: "BF8",  # gfx95
    }

    _CK_DTYPE_ALIASES = {
        "F8": "ck_tile::fp8_t",
        "BF8": "ck_tile::bf8_t",
        "F16": "ck_tile::half_t",
        "F32": "float",
        "BF16": "ck_tile::bfloat16_t",
    }

    # Bytes per element, used for the alignment and LDS budget math in the gemm
    # templates. Keys are _TORCH_DTYPE_TO_CK values. This table does not decide
    # which instances exist; see GEMM_DTYPES in ck_tile_universal_gemm_template.
    ck_dtype_to_size = {
        _TORCH_DTYPE_TO_CK[torch.float16]: 2,
        _TORCH_DTYPE_TO_CK[torch.bfloat16]: 2,
    }

    def header(self) -> IndentedBuffer:
        res = super().header()
        res.splice(
            """
                // CK headers
                #include "ck_tile/core.hpp"

            """
        )
        return res

    def globals(self) -> IndentedBuffer:
        res = super().globals()
        res.newline()
        for name, ctype in self._CK_DTYPE_ALIASES.items():
            res.writeline(f"using {name} = {ctype};")
        return res

    def torch_type_to_ck(self, node: IRNode, ptr: str) -> str:
        if node is None:
            return ptr
        else:
            return f"({self._TORCH_DTYPE_TO_CK.get(node.get_dtype())}*)({ptr})"
