/*
Copyright 2026 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 scaffolds

import (
	"fmt"
	"log/slog"
	"os"
	"os/exec"
	"path/filepath"

	"github.com/spf13/afero"

	"sigs.k8s.io/kubebuilder/v4/pkg/config"
	"sigs.k8s.io/kubebuilder/v4/pkg/machinery"
	"sigs.k8s.io/kubebuilder/v4/pkg/plugins"
	"sigs.k8s.io/kubebuilder/v4/pkg/plugins/optional/helm/v2alpha/scaffolds/internal"
)

const (
	defaultManifestsFile = "dist/install.yaml"
)

var _ plugins.Scaffolder = &chartScaffolder{}

type chartScaffolder struct {
	config        config.Config
	fs            machinery.Filesystem
	force         bool
	manifestsFile string
	outputDir     string
}

// NewChartScaffolder returns a new Scaffolder for Helm chart generation from kustomize output.
func NewChartScaffolder(cfg config.Config, force bool, manifestsFile, outputDir string) plugins.Scaffolder {
	return &chartScaffolder{
		config:        cfg,
		force:         force,
		manifestsFile: manifestsFile,
		outputDir:     outputDir,
	}
}

// InjectFS implements cmdutil.Scaffolder.
func (s *chartScaffolder) InjectFS(fs machinery.Filesystem) {
	s.fs = fs
}

// Scaffold generates the complete Helm chart from kustomize output.
func (s *chartScaffolder) Scaffold() error {
	slog.Info("Generating Helm Chart from kustomize output")

	if err := s.ensureChartDirectoryExists(); err != nil {
		return fmt.Errorf("failed to create chart directory: %w", err)
	}

	if s.manifestsFile == defaultManifestsFile {
		if err := s.generateKustomizeOutput(); err != nil {
			return fmt.Errorf("failed to generate kustomize output: %w", err)
		}
	}

	chartScaffolder := internal.NewChartScaffolder(internal.ChartScaffolderConfig{
		ProjectName:   s.config.GetProjectName(),
		ManifestsFile: s.manifestsFile,
		OutputDir:     s.outputDir,
		Force:         s.force,
	})

	builders, err := chartScaffolder.PrepareTemplates(s.fs)
	if err != nil {
		return fmt.Errorf("failed to prepare chart templates: %w", err)
	}

	scaffold := machinery.NewScaffold(s.fs, machinery.WithConfig(s.config))

	if err := scaffold.Execute(builders...); err != nil {
		return fmt.Errorf("failed to execute Helm chart templates: %w", err)
	}

	slog.Info("Helm Chart generation completed successfully")
	return nil
}

// generateKustomizeOutput runs make build-installer to generate the manifests file
func (s *chartScaffolder) generateKustomizeOutput() error {
	slog.Info("Generating kustomize output with make build-installer")

	// Check if Makefile exists
	if _, err := os.Stat("Makefile"); os.IsNotExist(err) {
		return fmt.Errorf("makefile not found in current directory")
	}

	// Run make build-installer
	cmd := exec.Command("make", "build-installer")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	if err := cmd.Run(); err != nil {
		return fmt.Errorf("failed to run make build-installer: %w", err)
	}

	// Verify that the manifests file was created
	if _, err := os.Stat(defaultManifestsFile); os.IsNotExist(err) {
		return fmt.Errorf("%s was not generated by make build-installer", defaultManifestsFile)
	}

	return nil
}

// ensureChartDirectoryExists creates the chart directory structure if it doesn't exist
func (s *chartScaffolder) ensureChartDirectoryExists() error {
	dirs := []string{
		filepath.Join(s.outputDir, "chart"),
		filepath.Join(s.outputDir, "chart", "templates"),
	}

	// Use injected filesystem if available, otherwise fall back to OS filesystem
	fs := s.fs.FS
	if fs == nil {
		fs = afero.NewOsFs()
	}

	for _, dir := range dirs {
		if err := fs.MkdirAll(dir, 0o755); err != nil {
			return fmt.Errorf("failed to create directory %s: %w", dir, err)
		}
	}

	return nil
}
