from typing import Union
from typing import Tuple
from typing import Optional


def utm_region_code(
    epsg: Union[int, Tuple[int, int, int]], tidx: Optional[Tuple[int, int]] = None
) -> str:
    """
    Construct UTM gridspec identifier.

    Examples:
    - 32751          -> "51S"
    - 32633, 10, 2   -> "33N_10_02"
    - 32603, (1, 2)  -> "03N_01_02"
    """
    if isinstance(epsg, tuple):
        tidx = epsg[1:]
        epsg = epsg[0]

    if 32601 <= epsg <= 32660:
        zone, code = epsg - 32600, "N"
    elif 32701 <= epsg <= 32760:
        zone, code = epsg - 32700, "S"
    else:
        raise ValueError(
            f"Not a utm epsg: {epsg}, valid ranges [32601, 32660] and [32701, 32760]"
        )

    if tidx is None:
        return f"{zone:02d}{code}"

    return f"{zone:02d}{code}_{tidx[0]:02d}_{tidx[1]:02d}"