import random
import requests
import os
import time

def create_github_issue(title, body, repo, token, labels=None):
    """Creates a GitHub issue using the provided information, optionally adding labels."""

    url = f"https://api.github.com/repos/{repo}/issues"
    headers = {
        "Accept": "application/vnd.github+json",
        "Authorization": f"Bearer {token}"
    }
    data = {
        "title": title,
        "body": body
    }

    # Add labels if provided
    if labels:
        data["labels"] = labels

    response = requests.post(url, headers=headers, json=data)

    if response.status_code == 201:
        print(f"Successfully created issue: {response.json()['html_url']}")
    else:
        print(f"Error creating issue: {response.json()['message']}")
        assert False


def gen_names_and_line():

  every = 5
  start = None
  starti = None
  bound = 444
  new_bound = bound
  for line, item in enumerate(SKIPLIST):
    if line < bound: continue

    if line % every == 4:
      starti = line
      start = item

    if line % every == 3:
      yield starti+14, line+14, start, item

    new_bound += 1
    print('new bound', new_bound)

  print('last_group')
  yield starti+14, line+14, start, item



def main():
  with open('template.t') as f:
    template = f.read()

  repo_owner = "pytorch" #os.getenv("GITHUB_REPO_OWNER")
  repo_name = "xla" #os.getenv("GITHUB_REPO_NAME")
  github_token = os.getenv("GITHUB_TOKEN")
  repository = f"{repo_owner}/{repo_name}"
  issue_labels = ["good first issue", "torchxla2"]

  if not all([repo_owner, repo_name, github_token]):
      raise ValueError("Required environment variables are missing. Please set GITHUB_REPO_OWNER, GITHUB_REPO_NAME, and GITHUB_TOKEN.")

  for i, (line, line2, name, name2) in enumerate(gen_names_and_line()):
    title = 'Op info test for `{name} .. {name2}`'.format(name=name, name2=name2)
    content = template.format(line_number=line, line_number2=line2, test_name=name, test_name2=name2)
    create_github_issue(title, content, repository, github_token, issue_labels)
    print('created, ', name)
    
  

  print('done')


SKIPLIST = [
    "__rpow__",  # NOTE: cannot fix because torch test case has undefined behavior 
                 # such as 0 to negative power.
    "_segment_reduce",
    "_upsample_bilinear2d_aa",
    "bincount", # NOTE: dtype for int input torch gives float. This is weird.
    "bitwise_left_shift",
    "bitwise_right_shift",
    "block_diag",
    "broadcast_tensors",
    "broadcast_to",
    "bucketize",
    "byte",
    "cat",
    "cauchy",
    "cdist",
    "cholesky",
    "cholesky_inverse",
    "cholesky_solve",
    "combinations",
    "complex",
    "constant_pad_nd",
    "copysign",
    "corrcoef",
    "count_nonzero",
    "cov",
    "cross",
    "cummax",
    "cummin",
    "cumprod",
    "cumsum",
    "diag",
    "diag_embed",
    "diagflat",
    "diagonal_copy",
    "diagonal_scatter",
    "diff",
    "digamma",
    "dist",
    "div",
    "empty_like",
    "empty_permuted",
    "empty_strided",
    "equal",
    "erfc",
    "erfinv",
    "exp2",
    "expand",
    "exponential",
    "fft.fft2",
    "fft.fft",
    "fft.fftn",
    "fft.hfft2",
    "fft.hfft",
    "fft.hfftn",
    "fft.ifft2",
    "fft.ifft",
    "fft.ifftn",
    "fft.ihfft2",
    "fft.ihfft",
    "fft.ihfftn",
    "fft.irfft2",
    "fft.irfft",
    "fft.irfftn",
    "fft.rfft2",
    "fft.rfft",
    "fft.rfftn",
    "floor_divide",
    "fmax",
    "fmin",
    "frexp",
    "full_like",
    "gather",
    "gcd",
    "geometric",
    "geqrf",
    "grid_sampler_2d",
    "heaviside",
    "histc",
    "histogram",
    "histogramdd",
    "hypot",
    "i0",
    "igamma",
    "igammac",
    "index_copy",
    "index_fill",
    "index_put",
    "index_reduce",
    "index_select",
    "isclose",
    "isin",
    "item",
    "kthvalue",
    "lcm",
    "lerp",
    "lgamma",
    "linalg.cholesky",
    "linalg.cholesky_ex",
    "linalg.cond",
    "linalg.cross",
    "linalg.det",
    "linalg.eig",
    "linalg.eigh",
    "linalg.eigvals",
    "linalg.eigvalsh",
    "linalg.householder_product",
    "linalg.inv",
    "linalg.inv_ex",
    "linalg.ldl_factor",
    "linalg.ldl_factor_ex",
    "linalg.ldl_solve",
    "linalg.lstsq",
    "linalg.lu",
    "linalg.lu_factor",
    "linalg.lu_factor_ex",
    "linalg.lu_solve",
    "linalg.matrix_norm",
    "linalg.matrix_power",
    "linalg.matrix_rank",
    "linalg.multi_dot",
    "linalg.norm",
    "linalg.pinv",
    "linalg.qr",
    "linalg.slogdet",
    "linalg.solve",
    "linalg.solve_ex",
    "linalg.solve_triangular",
    "linalg.svd",
    "linalg.svdvals",
    "linalg.tensorinv",
    "linalg.tensorsolve",
    "linalg.vander",
    "linalg.vector_norm",
    "linspace",
    "log_normal",
    "log_softmax",
    "logaddexp2",
    "logaddexp",
    "logcumsumexp",
    "logdet",
    "logspace",
    "lu",
    "lu_solve",
    "lu_unpack",
    "masked.amax",
    "masked.amin",
    "masked.argmax",
    "masked.argmin",
    "masked.cumprod",
    "masked.cumsum",
    "masked.log_softmax",
    "masked.logaddexp",
    "masked.logsumexp",
    "masked.mean",
    "masked.median",
    "masked.norm",
    "masked.normalize",
    "masked.prod",
    "masked_scatter",
    "masked_select",
    "masked.softmax",
    "masked.softmin",
    "masked.std",
    "masked.sum",
    "masked.var",
    "matrix_exp",
    "matmul",
    "max_pool2d_with_indices_backward",
    "max",
    "median",
    "min",
    "mode",
    "multinomial",
    "mvlgamma",
    "nanmedian",
    "nanquantile",
    "nansum",
    "narrow_copy",
    "narrow",
    "native_layer_norm",
    "new_empty",
    "new_empty_strided",
    "nextafter",
    "nn.functional.adaptive_avg_pool1d",
    "nn.functional.adaptive_avg_pool2d",
    "nn.functional.adaptive_avg_pool3d",
    "nn.functional.adaptive_max_pool1d",
    "nn.functional.adaptive_max_pool2d",
    "nn.functional.adaptive_max_pool3d",
    "nn.functional.alpha_dropout",
    "nn.functional.avg_pool1d",
    "nn.functional.avg_pool2d",
    "nn.functional.avg_pool3d",
    "nn.functional.batch_norm",
    "nn.functional.bilinear",
    "nn.functional.binary_cross_entropy",
    "nn.functional.conv2d",
    "nn.functional.conv3d",
    "nn.functional.conv_transpose1d",
    "nn.functional.conv_transpose2d",
    "nn.functional.conv_transpose3d",
    "nn.functional.cosine_embedding_loss",
    "nn.functional.cosine_similarity",
    "nn.functional.cross_entropy",
    "nn.functional.ctc_loss",
    "nn.functional.dropout2d",
    "nn.functional.dropout3d",
    "nn.functional.dropout",
    "nn.functional.embedding_bag",
    "nn.functional.embedding",
    "nn.functional.feature_alpha_dropout",
    "nn.functional.fractional_max_pool2d",
    "nn.functional.fractional_max_pool3d",
    "nn.functional.gaussian_nll_loss",
    "nn.functional.grid_sample",
    "nn.functional.group_norm",
    "nn.functional.hinge_embedding_loss",
    "nn.functional.instance_norm",
    "nn.functional.interpolate",
    "nn.functional.layer_norm",
    "nn.functional.leaky_relu",
    "nn.functional.linear",
    "nn.functional.logsigmoid",
    "nn.functional.margin_ranking_loss",
    "nn.functional.max_pool1d",
    "nn.functional.max_pool2d",
    "nn.functional.max_pool3d",
    "nn.functional.max_unpool1d",
    "nn.functional.max_unpool2d",
    "nn.functional.max_unpool3d",
    "nn.functional.multi_head_attention_forward",
    "nn.functional.multi_margin_loss",
    "nn.functional.multilabel_margin_loss",
    "nn.functional.multilabel_soft_margin_loss",
    "nn.functional.nll_loss",
    "nn.functional.normalize",
    "nn.functional.one_hot",
    "nn.functional.pad",
    "nn.functional.pairwise_distance",
    "nn.functional.pdist",
    "nn.functional.pixel_shuffle",
    "nn.functional.pixel_unshuffle",
    "nn.functional.poisson_nll_loss",
    "nn.functional.rrelu",
    "nn.functional.scaled_dot_product_attention",
    "nn.functional.softmin",
    "nn.functional.unfold",
    "nn.functional.upsample_nearest",
    "nonzero",
    "nonzero_static",
    "norm",
    "normal",
    "ones_like",
    "ormqr",
    "pca_lowrank",
    "pinverse",
    "polar",
    "polygamma",
    "prod",
    "put",
    "qr",
    "quantile",
    "rand_like",
    "randint_like",
    "randn_like",
    "renorm",
    "repeat_interleave",
    "resize_",
    "resize_as_",
    "rot90",
    "rsub",
    "scatter_add",
    "scatter",
    "scatter_reduce",
    "searchsorted",
    "select_scatter",
    "signbit",
    "softmax",
    "sort",
    "special.airy_ai",
    "special.bessel_j0",
    "special.bessel_j1",
    "special.bessel_y0",
    "special.bessel_y1",
    "special.chebyshev_polynomial_t",
    "special.chebyshev_polynomial_u",
    "special.erfcx",
    "special.hermite_polynomial_h",
    "special.hermite_polynomial_he",
    "special.i0e",
    "special.i1",
    "special.i1e",
    "special.laguerre_polynomial_l",
    "special.log_ndtr",
    "special.modified_bessel_i0",
    "special.modified_bessel_i1",
    "special.modified_bessel_k0",
    "special.modified_bessel_k1",
    "special.ndtri",
    "special.polygamma",
    "special.scaled_modified_bessel_k0",
    "special.scaled_modified_bessel_k1",
    "special.spherical_bessel_j0",
    "special.zeta",
    "squeeze",
    "stft",
    "sub",
    "svd",
    "svd_lowrank",
    "take_along_dim",
    "take",
    "tensor_split",
    "to_sparse",
    "topk",
    "trace",
    "triangular_solve",
    "triu",
    "unbind",
    "unfold_copy",
    "unfold",
    "uniform",
    "unique_consecutive",
    "unique",
    "unravel_index",
    "var_mean",
    "zero_",
    "zeros_like",
    "argwhere",
    "cumulative_trapezoid",
    "expand_as",
    "mean",
    "nanmean",
    "trapezoid",
    "trapz",
    "H",
    "T",
    "_softmax_backward_data",
    "addcdiv",
    "addcmul",
    "arange",
    "atan2",
    "atleast_1d",
    "atleast_2d",
    "atleast_3d",
    "bfloat16",
    "bmm",
    "broadcast_shapes",
    "cartesian_prod",
    "cdouble",
    "ceil",
    "cfloat",
    "chalf",
    "char",
    "chunk",
    "clamp",
    "clamp_max",
    "clamp_min",
    "clone",
    "column_stack",
    "conj",
    "conj_physical",
    "contiguous",
    "deg2rad",
    "diagonal",
    "dot",
    "dsplit",
    "dstack",
    "einsum",
    "erf",
    "exp",
    "expm1",
    "eye",
    "fft.fftshift",
    "fft.ifftshift",
    "fill",
    "flatten",
    "flip",
    "fliplr",
    "flipud",
    "fmod",
    "frac",
    "full",
    "gradient",
    "hsplit",
    "hstack",
    "index_add",
    "inner",
    "kron",
    "ldexp",
    "linalg.diagonal",
    "linalg.vecdot",
    "mH",
    "mT",
    "masked_fill",
    "meshgrid",
    "movedim",
    "msort",
    "mul",
    "mv",
    "nan_to_num",
    "native_dropout_backward",
    "new_full",
    "new_ones",
    "new_zeros",
    "nn.functional.binary_cross_entropy_with_logits",
    "nn.functional.celu",
    "nn.functional.conv1d",
    "nn.functional.elu",
    "nn.functional.gelu",
    "nn.functional.glu",
    "nn.functional.hardshrink",
    "nn.functional.hardsigmoid",
    "nn.functional.hardswish",
    "nn.functional.hardtanh",
    "nn.functional.huber_loss",
    "nn.functional.kl_div",
    "nn.functional.l1_loss",
    "nn.functional.local_response_norm",
    "nn.functional.mish",
    "nn.functional.mse_loss",
    "nn.functional.prelu",
    "nn.functional.relu6",
    "nn.functional.relu",
    "nn.functional.selu",
    "nn.functional.silu",
    "nn.functional.smooth_l1_loss",
    "nn.functional.soft_margin_loss",
    "nn.functional.softplus",
    "nn.functional.softshrink",
    "nn.functional.softsign",
    "nn.functional.tanhshrink",
    "nn.functional.threshold",
    "nn.functional.triplet_margin_loss",
    "nn.functional.triplet_margin_with_distance_loss",
    "nn.functional.upsample_bilinear",
    "ones",
    "outer",
    "permute",
    "positive",
    "rad2deg",
    "randint",
    "ravel",
    "reciprocal",
    "remainder",
    "repeat",
    "reshape_as",
    "reshape",
    "resolve_conj",
    "resolve_neg",
    "roll",
    "rsqrt",
    "scalar_tensor",
    "signal.windows.bartlett",
    "signal.windows.blackman",
    "signal.windows.cosine",
    "signal.windows.exponential",
    "signal.windows.gaussian",
    "signal.windows.general_cosine",
    "signal.windows.general_hamming",
    "signal.windows.hamming",
    "signal.windows.hann",
    "signal.windows.kaiser",
    "signal.windows.nuttall",
    "slice",
    "slice_scatter",
    "sparse.mm",
    "sparse.sampled_addmm",
    "special.entr",
    "special.ndtr",
    "special.xlog1py",
    "split",
    "split_with_sizes",
    "split_with_sizes_copy",
    "square",
    "stack",
    "sum_to_size",
    "tensordot",
    "tile",
    "tril",
    "tril_indices",
    "triu_indices",
    "true_divide",
    "trunc",
    "unflatten",
    "unsafe_chunk",
    "unsafe_split",
    "unsqueeze",
    "vdot",
    "view_as_complex",
    "view_as",
    "view_copy",
    "view",
    "vsplit",
    "vstack",
    "zeros",
]

if __name__ == '__main__':
  main()
