// Copyright 2022 Woodpecker Authors
// Copyright 2018 Drone.IO Inc.
//
// 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 builder

import (
	"fmt"
	"maps"
	"slices"
	"strconv"
	"strings"

	"github.com/oklog/ulid/v2"
	"github.com/rs/zerolog/log"
	"go.uber.org/multierr"

	"go.woodpecker-ci.org/woodpecker/v3/pipeline"
	backend_types "go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/types"
	pipeline_errors "go.woodpecker-ci.org/woodpecker/v3/pipeline/errors"
	"go.woodpecker-ci.org/woodpecker/v3/pipeline/frontend/metadata"
	"go.woodpecker-ci.org/woodpecker/v3/pipeline/frontend/yaml"
	"go.woodpecker-ci.org/woodpecker/v3/pipeline/frontend/yaml/compiler"
	"go.woodpecker-ci.org/woodpecker/v3/pipeline/frontend/yaml/linter"
	"go.woodpecker-ci.org/woodpecker/v3/pipeline/frontend/yaml/matrix"
	yaml_types "go.woodpecker-ci.org/woodpecker/v3/pipeline/frontend/yaml/types"
)

// PipelineBuilder Takes the yaml configs and some metadata and returns the internal data model to execute a pipeline.
type PipelineBuilder struct {
	Yamls               []*YamlFile
	Envs                map[string]string
	DefaultLabels       map[string]string
	RepoTrusted         *metadata.TrustedConfiguration
	TrustedClonePlugins []string
	PrivilegedPlugins   []string
	CompilerOptions     []compiler.Option
	GetWorkflowMetadata func(workflow *Workflow) metadata.Metadata
}

func (b *PipelineBuilder) Build() (items []*Item, errorsAndWarnings error) {
	b.Yamls = SortYamlFilesByName(b.Yamls)

	pidSequence := 1

	for _, y := range b.Yamls {
		// matrix axes
		axes, err := matrix.ParseString(string(y.Data))
		if err != nil {
			return nil, err
		}
		if len(axes) == 0 {
			axes = append(axes, matrix.Axis{})
		}

		for i, axis := range axes {
			workflow := &Workflow{
				PID:     pidSequence,
				Environ: axis,
				Name:    SanitizePath(y.Name),
			}
			if len(axes) > 1 {
				workflow.AxisID = i + 1
			}
			item, err := b.genItemForWorkflow(workflow, axis, string(y.Data))
			if err != nil && pipeline_errors.HasBlockingErrors(err) {
				return nil, err
			} else if err != nil {
				errorsAndWarnings = multierr.Append(errorsAndWarnings, err)
			}

			if item == nil {
				continue
			}
			items = append(items, item)
			pidSequence++
		}

		// TODO: add summary workflow that send status back based on workflows generated by matrix function
		// depend on https://github.com/woodpecker-ci/woodpecker/issues/778
	}

	items = filterMissingDependencies(items)

	return items, errorsAndWarnings
}

func (b *PipelineBuilder) genItemForWorkflow(workflow *Workflow, axis matrix.Axis, data string) (item *Item, errorsAndWarnings error) {
	workflowMetadata := b.GetWorkflowMetadata(workflow)
	environ := b.environmentVariables(workflowMetadata, axis)

	// add global environment variables for substituting
	for k, v := range b.Envs {
		if _, exists := environ[k]; exists {
			// don't override existing values
			continue
		}
		environ[k] = v
	}

	// substitute vars
	substituted, err := metadata.EnvVarSubst(data, environ)
	if err != nil {
		return nil, multierr.Append(errorsAndWarnings, err)
	}

	// parse yaml pipeline
	parsed, err := yaml.ParseString(substituted)
	if err != nil {
		return nil, &pipeline_errors.PipelineError{Message: err.Error(), Type: pipeline_errors.PipelineErrorTypeCompiler}
	}

	// lint pipeline
	errorsAndWarnings = multierr.Append(errorsAndWarnings, linter.New(
		linter.WithTrusted(linter.TrustedConfiguration{
			Network:  b.RepoTrusted.Network,
			Volumes:  b.RepoTrusted.Volumes,
			Security: b.RepoTrusted.Security,
		}),
		linter.PrivilegedPlugins(b.PrivilegedPlugins),
		linter.WithTrustedClonePlugins(b.TrustedClonePlugins),
	).Lint([]*linter.WorkflowConfig{{
		Workflow:  parsed,
		File:      workflow.Name,
		RawConfig: data,
	}}))
	if pipeline_errors.HasBlockingErrors(errorsAndWarnings) {
		return nil, errorsAndWarnings
	}

	// checking if filtered.
	if match, err := parsed.When.Match(workflowMetadata, true, environ); !match && err == nil {
		log.Debug().Str("pipeline", workflow.Name).Msg(
			"marked as skipped, does not match metadata",
		)
		return nil, nil
	} else if err != nil {
		log.Debug().Str("pipeline", workflow.Name).Msg(
			"pipeline config could not be parsed",
		)
		return nil, multierr.Append(errorsAndWarnings, err)
	}

	ir, err := b.toInternalRepresentation(parsed, environ, workflowMetadata, workflow.ID)
	if err != nil {
		return nil, multierr.Append(errorsAndWarnings, err)
	}

	if len(ir.Stages) == 0 {
		return nil, nil
	}

	item = &Item{
		Workflow:  workflow,
		Config:    ir,
		Labels:    parsed.Labels,
		DependsOn: parsed.DependsOn,
		// TODO: remove in next major.
		RunsOn: parsed.RunsOn, //nolint:staticcheck
	}
	if len(item.Labels) == 0 {
		item.Labels = make(map[string]string, len(b.DefaultLabels))
		// Set default labels if no labels are defined in the pipeline
		maps.Copy(item.Labels, b.DefaultLabels)
	}

	if !slices.Contains(item.RunsOn, "failure") && parsed.When.IncludesStatusFailure(workflowMetadata, true, environ) {
		item.RunsOn = append(item.RunsOn, "failure")
	}
	if !slices.Contains(item.RunsOn, "success") && parsed.When.IncludesStatusFailure(workflowMetadata, true, environ) {
		item.RunsOn = append(item.RunsOn, "success")
	}

	// "woodpecker-ci.org" namespace is reserved for internal use — drop any
	// user-defined labels that try to use it.
	for key := range item.Labels {
		if strings.HasPrefix(key, pipeline.InternalLabelPrefix) {
			log.Debug().Str("label", key).Msg("dropped pipeline label with reserved prefix woodpecker-ci.org")
			delete(item.Labels, key)
		}
	}

	// Stamp Woodpecker-managed internal labels onto the item so that the server
	// and backends can use them for routing, observability, etc.
	item.Labels[pipeline.LabelForgeRemoteID] = workflowMetadata.Forge.Type
	item.Labels[pipeline.LabelRepoForgeID] = workflowMetadata.Repo.RemoteID
	item.Labels[pipeline.LabelRepoID] = strconv.FormatInt(workflowMetadata.Repo.ID, 10)
	item.Labels[pipeline.LabelRepoName] = workflowMetadata.Repo.Name
	item.Labels[pipeline.LabelRepoFullName] = workflowMetadata.Repo.Owner + "/" + workflowMetadata.Repo.Name
	item.Labels[pipeline.LabelBranch] = workflowMetadata.Repo.Branch
	item.Labels[pipeline.LabelOrgID] = strconv.FormatInt(workflowMetadata.Repo.OrgID, 10)

	return item, errorsAndWarnings
}

func (b *PipelineBuilder) environmentVariables(metadata metadata.Metadata, axis matrix.Axis) map[string]string {
	environ := metadata.Environ()
	maps.Copy(environ, axis)
	return environ
}

func (b *PipelineBuilder) toInternalRepresentation(parsed *yaml_types.Workflow, environ map[string]string, metadata metadata.Metadata, workflowID int64) (*backend_types.Config, error) {
	options := []compiler.Option{}
	options = append(
		options,
		compiler.WithEnviron(environ),
		compiler.WithEnviron(b.Envs),
		compiler.WithEscalated(b.PrivilegedPlugins...),
		compiler.WithTrustedClonePlugins(b.TrustedClonePlugins),
		compiler.WithPrefix(
			fmt.Sprintf(
				"wp_%s_%d",
				strings.ToLower(ulid.Make().String()),
				workflowID,
			),
		),
		compiler.WithMetadata(metadata),
		compiler.WithTrustedSecurity(b.RepoTrusted.Security),
	)

	// by adding the passed in options last, we allow them
	// to override any of the default options set above
	options = append(options, b.CompilerOptions...)

	return compiler.New(options...).Compile(parsed)
}
