//go:generate go run generate_patterns.go
package main

import (
	"fmt"
	"os"
	"strings"
	"text/template"
	"time"

	"github.com/anchore/grant/internal/spdxlicense"
)

const (
	generates = "../patterns.go"
)

var commonCase = []string{
	"LICENSE",
	"LICENSE.*",
	"LICENCE",
	"LICENCE.*",
	"COPYING",
	"COPYING.*",
	"NOTICE",
	"NOTICE.*",
}

var codeTemplate = template.Must(template.New("patterns.go").Parse(`// Code generated by internal/licensepatterns/generate/generate_patterns.go; DO NOT EDIT.
// This file was generated by go generate; DO NOT EDIT; {{ .Timestamp }}
package licensepatterns

// Patterns contains all license file patterns used for searching
var Patterns = []string{
{{- range .Patterns }}
	{{ printf "%q" . }},
{{- end }}
}
`))

func main() {
	if err := generate(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Println("generated", generates)
}

func generate() error {
	patterns := generateLicensePatterns()

	if err := os.Remove(generates); err != nil && !os.IsNotExist(err) {
		fmt.Println("Error deleting existing file:", err)
		return err
	}

	f, err := os.Create(generates)
	if err != nil {
		return err
	}
	defer func() { _ = f.Close() }()

	return codeTemplate.Execute(f, struct {
		Timestamp string
		Patterns  []string
	}{
		Timestamp: time.Now().UTC().Format(time.RFC3339),
		Patterns:  patterns,
	})
}

// generateLicensePatterns creates file patterns based on SPDX license IDs
func generateLicensePatterns() []string {
	patterns := make([]string, 0)

	// Add common patterns
	patterns = append(patterns, commonCase...)

	// Get all SPDX license keys and create patterns
	licenseKeys := spdxlicense.GetAllLicenseKeys()
	for _, key := range licenseKeys {
		// Create case-insensitive patterns for each license ID
		// e.g., "gpl-3.0" becomes patterns for GPL-3.0, gpl-3.0, etc.
		upper := strings.ToUpper(key)
		patterns = append(patterns,
			fmt.Sprintf("*%s*", upper),
			fmt.Sprintf("*%s*", key),
			upper,
			key,
		)
	}

	return patterns
}
