/*
Copyright 2025 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 generators

import (
	"fmt"
	"io"
	"strings"

	"k8s.io/gengo/v2"
	"k8s.io/gengo/v2/generator"
	"k8s.io/gengo/v2/namer"
	"k8s.io/gengo/v2/types"
	"k8s.io/klog/v2"
)

const (
	tagModelPackage = "k8s:openapi-model-package"
)

func extractOpenAPISchemaNamePackage(comments []string) (string, error) {
	v, err := singularTag(tagModelPackage, comments)
	if v == nil || err != nil {
		return "", err
	}
	return v.Value, nil
}

func singularTag(tagName string, comments []string) (*gengo.Tag, error) {
	tags, err := gengo.ExtractFunctionStyleCommentTags("+", []string{tagName}, comments)
	if err != nil {
		return nil, err
	}
	if len(tags) == 0 {
		return nil, nil
	}
	if len(tags) > 1 {
		return nil, fmt.Errorf("multiple %s tags found", tagName)
	}
	tag := tags[tagName]
	if len(tag) == 0 {
		return nil, nil
	}
	if len(tag) > 1 {
		klog.V(5).Infof("multiple %s tags found, using the first one", tagName)
	}
	value := tag[0]
	return &value, nil
}

// genSchemaName produces a file with autogenerated openapi schema name functions.
type genSchemaName struct {
	generator.GoGenerator
	targetPackage            string
	imports                  namer.ImportTracker
	typesForInit             []*types.Type
	openAPISchemaNamePackage string
}

// NewSchemaNameGen creates a generator
func NewSchemaNameGen(outputFilename, targetPackage string, openAPISchemaNamePackage string) generator.Generator {
	return &genSchemaName{
		GoGenerator: generator.GoGenerator{
			OutputFilename: outputFilename,
		},
		targetPackage:            targetPackage,
		imports:                  generator.NewImportTracker(),
		typesForInit:             make([]*types.Type, 0),
		openAPISchemaNamePackage: openAPISchemaNamePackage,
	}
}

func (g *genSchemaName) Namers(c *generator.Context) namer.NameSystems {
	return namer.NameSystems{
		"public": namer.NewPublicNamer(1),
		"local":  namer.NewPublicNamer(0),
		"raw":    namer.NewRawNamer("", nil),
	}
}

func (g *genSchemaName) Filter(c *generator.Context, t *types.Type) bool {
	// Filter out types not being processed or not copyable within the package.
	if !isSchemaNameType(t) {
		klog.V(2).Infof("Type %v is not a valid target for OpenAPI schema name", t)
		return false
	}
	g.typesForInit = append(g.typesForInit, t)
	return true
}

// isSchemaNameType indicates whether or not a type could be used to serve an API.
func isSchemaNameType(t *types.Type) bool {
	// Filter out private types.
	if namer.IsPrivateGoName(t.Name.Name) {
		return false
	}

	for t.Kind == types.Alias {
		t = t.Underlying
	}

	if t.Kind != types.Struct {
		return false
	}
	return true
}

func (g *genSchemaName) isOtherPackage(pkg string) bool {
	if pkg == g.targetPackage {
		return false
	}
	if strings.HasSuffix(pkg, ""+g.targetPackage+"") {
		return false
	}
	return true
}

func (g *genSchemaName) Imports(c *generator.Context) (imports []string) {
	importLines := []string{}
	for _, singleImport := range g.imports.ImportLines() {
		if g.isOtherPackage(singleImport) {
			importLines = append(importLines, singleImport)
		}
	}
	return importLines
}

func (g *genSchemaName) Init(c *generator.Context, w io.Writer) error {
	return nil
}

func (g *genSchemaName) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {
	klog.V(3).Infof("Generating openapi schema name for type %v", t)

	openAPISchemaNamePackage := g.openAPISchemaNamePackage
	v, err := singularTag(tagModelPackage, t.CommentLines)
	if err != nil {
		return fmt.Errorf("type %v: invalid %s:%v", t.Name, tagModelPackage, err)
	}
	if v != nil && v.Value != "" {
		openAPISchemaNamePackage = v.Value
	}

	if openAPISchemaNamePackage == "" {
		return nil
	}

	schemaName := openAPISchemaNamePackage + "." + t.Name.Name

	a := map[string]interface{}{
		"type":       t,
		"schemaName": schemaName,
	}

	sw := generator.NewSnippetWriter(w, c, "$", "$")

	sw.Do("// OpenAPIModelName returns the OpenAPI model name for this type.\n", a)
	sw.Do("func (in $.type|local$) OpenAPIModelName() string {\n", a)
	sw.Do("\treturn \"$.schemaName$\"\n", a)
	sw.Do("}\n\n", nil)

	return sw.Error()
}
