//go:build generate
// +build generate

package main

import (
	"bytes"
	"encoding/csv"
	"fmt"
	"log"
	"os"
	"sort"
	"strings"
	"text/template"

	"github.com/hashicorp/terraform-provider-aws/names"
)

const (
	filename      = `../../../.github/labeler-issue-triage.yml`
	namesDataFile = "../../../names/names_data.csv"
)

type ServiceDatum struct {
	ProviderPackage string
	RegExp          string
}

type TemplateData struct {
	Services []ServiceDatum
}

func main() {
	fmt.Printf("Generating %s\n", strings.TrimPrefix(filename, "../../../"))

	f, err := os.Open(namesDataFile)
	if err != nil {
		log.Fatal(err)
	}

	defer f.Close()

	csvReader := csv.NewReader(f)

	data, err := csvReader.ReadAll()
	if err != nil {
		log.Fatal(err)
	}

	td := TemplateData{}

	for i, l := range data {
		if i < 1 { // no header
			continue
		}

		if l[names.ColExclude] != "" && l[names.ColAllowedSubcategory] == "" {
			continue
		}

		if l[names.ColProviderPackageActual] == "" && l[names.ColProviderPackageCorrect] == "" {
			continue
		}

		if l[names.ColResourcePrefixActual] == "" && l[names.ColResourcePrefixCorrect] == "" {
			continue
		}

		p := l[names.ColProviderPackageCorrect]

		if l[names.ColProviderPackageActual] != "" {
			p = l[names.ColProviderPackageActual]
		}

		rp := l[names.ColResourcePrefixCorrect]

		if l[names.ColResourcePrefixActual] != "" {
			rp = l[names.ColResourcePrefixActual]
		}

		s := ServiceDatum{
			ProviderPackage: p,
			RegExp:          `((\*|-)\s*` + "`" + `?|(data|resource)\s+"?)` + rp,
		}

		td.Services = append(td.Services, s)
	}

	sort.SliceStable(td.Services, func(i, j int) bool {
		return td.Services[i].ProviderPackage < td.Services[j].ProviderPackage
	})

	writeTemplate(tmpl, "issuelabeler", td)
}

func writeTemplate(body string, templateName string, td TemplateData) {
	// If the file doesn't exist, create it, or append to the file
	f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		log.Fatalf("error opening file (%s): %s", filename, err)
	}

	tplate, err := template.New(templateName).Parse(body)
	if err != nil {
		log.Fatalf("error parsing template: %s", err)
	}

	var buffer bytes.Buffer
	err = tplate.Execute(&buffer, td)
	if err != nil {
		log.Fatalf("error executing template: %s", err)
	}

	if _, err := f.Write(buffer.Bytes()); err != nil {
		f.Close()
		log.Fatalf("error writing to file (%s): %s", filename, err)
	}

	if err := f.Close(); err != nil {
		log.Fatalf("error closing file (%s): %s", filename, err)
	}
}

var tmpl = `# Generated by internal/generate/issuelabels/main.go; DO NOT EDIT.
bug:
  # Bug Issue Template:
  #   [Bug]:
  # General:
  #   panic:
  # AWS SDK Go:
  #   ValidationException:.*failed to satisfy constraint: Member must not be null
  # Terraform CLI:
  #   Provider produced inconsistent final plan
  #   Provider produced inconsistent result after apply
  #   produced an invalid new value
  #   produced an unexpected new value
  # Terraform Plugin SDK:
  #   doesn't support update
  #   Invalid address to set
  - "(\\[Bug\\]:|doesn't support update|failed to satisfy constraint: Member must not be null|Invalid address to set|panic:|produced an (invalid|unexpected) new value|Provider produced inconsistent (final plan|result after apply))"
crash:
  - 'panic:'
sweeper:
  - 'sweeper'
skaff:
  - 'skaff'
#
# AWS Per-Service Labeling
#
# Catch the following:
# 1. List items (* or -) with aws_XXX resource prefix (with or without backticks)
# 2. "data aws_XXX" or "resource aws_XXX"
{{- range .Services }}
service/{{ .ProviderPackage }}:
  - '{{ .RegExp }}'
{{- end }}
`
