// Copyright 2020-2024, Pulumi Corporation.
//
// 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 gen

import (
	"fmt"

	"github.com/hashicorp/hcl/v2"
	"github.com/hashicorp/hcl/v2/hclsyntax"
	"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model"
	"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/syntax"
)

type splatTemp struct {
	Name  string
	Value *model.SplatExpression
}

func (st *splatTemp) Type() model.Type {
	return st.Value.Type()
}

func (st *splatTemp) Traverse(traverser hcl.Traverser) (model.Traversable, hcl.Diagnostics) {
	return st.Type().Traverse(traverser)
}

func (st *splatTemp) SyntaxNode() hclsyntax.Node {
	return syntax.None
}

type splatSpiller struct {
	temps []*splatTemp
	count int
}

func (ss *splatSpiller) spillExpression(x model.Expression) (model.Expression, hcl.Diagnostics) {
	var temp *splatTemp
	switch x := x.(type) {
	case *model.SplatExpression:
		temp = &splatTemp{
			Name:  fmt.Sprintf("splat%d", ss.count),
			Value: x,
		}
		ss.temps = append(ss.temps, temp)
		ss.count++
	default:
		return x, nil
	}
	return &model.ScopeTraversalExpression{
		RootName:  temp.Name,
		Traversal: hcl.Traversal{hcl.TraverseRoot{Name: ""}},
		Parts:     []model.Traversable{temp},
	}, nil
}

func (g *generator) rewriteSplat(
	x model.Expression,
	spiller *splatSpiller,
) (model.Expression, []*splatTemp, hcl.Diagnostics) {
	spiller.temps = nil
	x, diags := model.VisitExpression(x, spiller.spillExpression, nil)

	return x, spiller.temps, diags
}