/*
Copyright 2015 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Package gengo is a code-generation framework.
package gengo

import (
	"bytes"
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"k8s.io/gengo/v2/generator"
	"k8s.io/gengo/v2/namer"
	"k8s.io/gengo/v2/parser"
)

// StdBuildTag is a suggested build-tag which tools can use both as an argument
// to GoBoilerplate and to Execute.
const StdBuildTag = "ignore_autogenerated"

// StdGeneratedBy is a suggested "generated by" line which tools can use as an
// argument to GoBoilerplate.
const StdGeneratedBy = "// Code generated by GENERATOR_NAME. DO NOT EDIT."

// GoBoilerplate returns the Go file header:
// - an optional build tag (negative, set it to ignore generated code)
// - an optional boilerplate file
// - an optional "generated by" comment
func GoBoilerplate(headerFile, buildTag, generatedBy string) ([]byte, error) {
	buf := bytes.Buffer{}

	if buildTag != "" {
		buf.WriteString(
			fmt.Sprintf("//go:build !%s\n// +build !%s\n\n", buildTag, buildTag))
	}

	if headerFile != "" {
		b, err := os.ReadFile(headerFile)
		if err != nil {
			return nil, err
		}
		b = bytes.ReplaceAll(b, []byte("YEAR"), []byte(strconv.Itoa(time.Now().UTC().Year())))
		buf.Write(b)
		buf.WriteByte('\n')
	}

	if generatedBy != "" {
		generatorName := filepath.Base(os.Args[0])
		// Strip the extension from the name to normalize output between *nix and Windows.
		generatorName = generatorName[:len(generatorName)-len(filepath.Ext(generatorName))]
		generatedByComment := strings.ReplaceAll(generatedBy, "GENERATOR_NAME", generatorName)
		buf.WriteString(fmt.Sprintf("%s\n\n", generatedByComment))
	}

	return buf.Bytes(), nil
}

// Execute implements most of a tool's main loop.
func Execute(nameSystems namer.NameSystems, defaultSystem string, getTargets func(*generator.Context) []generator.Target, buildTag string, patterns []string) error {
	var buildTags []string
	if buildTag != "" {
		buildTags = append(buildTags, buildTag)
	}

	p := parser.NewWithOptions(parser.Options{BuildTags: buildTags})
	if err := p.LoadPackages(patterns...); err != nil {
		return fmt.Errorf("failed making a parser: %v", err)
	}

	c, err := generator.NewContext(p, nameSystems, defaultSystem)
	if err != nil {
		return fmt.Errorf("failed making a context: %v", err)
	}

	targets := getTargets(c)
	if err := c.ExecuteTargets(targets); err != nil {
		return fmt.Errorf("failed executing generator: %v", err)
	}

	return nil
}
