// Copyright 2024 The Hugo Authors. All rights reserved.
//
// 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 js

import (
	"fmt"
	"path"
	"path/filepath"
	"regexp"
	"strings"

	"github.com/evanw/esbuild/pkg/api"
	"github.com/gohugoio/hugo/hugolib/filesystems"
	"github.com/gohugoio/hugo/internal/js/esbuild"

	"github.com/gohugoio/hugo/resources"
	"github.com/gohugoio/hugo/resources/resource"
)

// Client context for ESBuild.
type Client struct {
	c *esbuild.BuildClient
}

// New creates a new client context.
func New(fs *filesystems.SourceFilesystem, rs *resources.Spec, cssMode bool) *Client {
	return &Client{
		c: esbuild.NewBuildClient(fs, rs, cssMode),
	}
}

// Process processes a resource with the user provided options.
func (c *Client) Process(res resources.ResourceTransformer, opts map[string]any) (resource.Resource, error) {
	return res.Transform(
		&buildTransformation{c: c, optsm: opts},
	)
}

func (c *Client) transform(opts esbuild.Options, transformCtx *resources.ResourceTransformationCtx) (api.BuildResult, error) {
	if transformCtx.DependencyManager != nil {
		opts.DependencyManager = transformCtx.DependencyManager
	}

	opts.StdinSourcePath = transformCtx.SourcePath

	result, err := c.c.Build(opts)
	if err != nil {
		return result, err
	}

	hasLinkedSourceMap := opts.ExternalOptions.SourceMap == "linked"
	hasSourceMap := hasLinkedSourceMap || opts.ExternalOptions.SourceMap == "external"

	// Classify output files by path rather than relying on array ordering,
	// which esbuild does not guarantee.
	var mainOutput []byte
	outDir := path.Dir(transformCtx.OutPath)
	for _, file := range result.OutputFiles {
		basePath := path.Base(filepath.ToSlash(file.Path))
		if strings.HasSuffix(basePath, ".map") {
			if hasSourceMap {
				if err = transformCtx.PublishSourceMap(file.Contents); err != nil {
					return result, err
				}
			}
		} else if isStdinEntryOutput(basePath) {
			mainOutput = file.Contents
		} else {
			// File-loader artifact; publish directly.
			target := path.Join(outDir, basePath)
			if err = transformCtx.PublishTo(target, file.Contents); err != nil {
				return result, err
			}
		}
	}

	if mainOutput == nil {
		return result, fmt.Errorf("esbuild: entry point output not found")
	}

	if hasLinkedSourceMap {
		symPath := path.Base(transformCtx.OutPath) + ".map"
		if opts.IsCSS {
			re := regexp.MustCompile(`/\*# sourceMappingURL=.*\n?`)
			mainOutput = re.ReplaceAll(mainOutput, []byte("/*# sourceMappingURL="+symPath+" */\n"))
		} else {
			re := regexp.MustCompile(`//# sourceMappingURL=.*\n?`)
			mainOutput = re.ReplaceAll(mainOutput, []byte("//# sourceMappingURL="+symPath+"\n"))
		}
	}

	if _, err = transformCtx.To.Write(mainOutput); err != nil {
		return result, err
	}

	return result, nil
}

// isStdinEntryOutput reports whether basePath is the entry-point output
// generated by esbuild when using stdin mode (e.g. "stdin.js", "stdin.css").
func isStdinEntryOutput(basePath string) bool {
	return strings.HasPrefix(basePath, "stdin.")
}
