package generator

import (
	
	
	
	
	
	
	
	

	

	amhelp 

	am 
)

type S = am.S

func ( string,  string) error {
	if  == "" {
		 = os.Getenv("GOPACKAGE")
	}
	 := strings.Split(, "/")
	 := [len()-1] + ".gen.go"
	return os.WriteFile(, []byte(), 0o644)
}

type SchemaV3 struct {
	ExportName string
	States     am.States
	Schema     am.Schema
	Groups     any
}

// GenSchemaV3 generates a status v1 schema from an initialized v2 schema.
func ( []SchemaV3) string {
	// gen intro
	 := jen.NewFile("states")

	// Add the build tag at the very top of the file
	.HeaderComment("Code generated by am-gen; DO NOT EDIT.")
	.HeaderComment("//go:build tinygo")

	 := "github.com/pancsta/asyncmachine-go/pkg/machine"
	.ImportAlias(, "am")

	// type S = am.S
	.Comment("S is a type alias for a list of state names.")
	.Type().Id("S").Op("=").Qual(, "S")

	.Line()

	 := []string{}

	for ,  := range  {
		 := .ExportName
		 := .States
		 := .Schema
		 := .Groups
		 := ToSuffix()
		 := 
		 := 2
		for slices.Contains(, ) {
			 =  + strconv.Itoa()
			++
		}
		 = append(, )

		// definitions
		 := []jen.Code{}
		 := []jen.Code{}
		 := jen.Dict{}

		// exports
		 := jen.Dict{}
		 := jen.Dict{}

		// values init()
		 := []jen.Code{}
		 := jen.Dict{}
		 := []jen.Code{}

		// states and schema

		for ,  := range .Names() {
			 = append(, jen.Lit())
			if  != am.StateException {
				 = append(, jen.Id().String())
				[jen.Id()] = jen.Lit()
			}

			 := jen.Dict{}
			 := []
			if .Auto {
				[jen.Id("Auto")] = jen.Lit(true)
			}
			if .Multi {
				[jen.Id("Multi")] = jen.Lit(true)
			}
			if .Add != nil {
				 := []jen.Code{}
				for ,  := range .Add {
					if slices.Contains(.Names(), ) {
						 = append(, jen.Id("ss"+).Dot())

						// dynamic binding
					} else {
						 = append(, jen.Lit())
					}
				}
				[jen.Id("Add")] = jen.Id("S").Values(...)
			}
			if .Require != nil {
				 := []jen.Code{}
				for ,  := range .Require {
					if slices.Contains(.Names(), ) {
						 = append(, jen.Id("ss"+).Dot())

						// dynamic binding
					} else {
						 = append(, jen.Lit())
					}
				}
				[jen.Id("Require")] = jen.Id("S").Values(...)
			}
			if .Remove != nil {
				 := []jen.Code{}
				for ,  := range .Remove {
					if slices.Contains(.Names(), ) {
						 = append(, jen.Id("ss"+).Dot())

						// dynamic binding
					} else {
						 = append(, jen.Lit())
					}
				}
				[jen.Id("Remove")] = jen.Id("S").Values(...)
			}
			if .After != nil {
				 := []jen.Code{}
				for ,  := range .After {
					if slices.Contains(.Names(), ) {
						 = append(, jen.Id("ss"+).Dot())

						// dynamic binding
					} else {
						 = append(, jen.Lit())
					}
				}
				[jen.Id("After")] = jen.Id("S").Values(...)
			}

			[jen.Id("ss"+).Dot()] = jen.Values()
		}

		// groups

		for ,  := range ExtractGroupsOrdered() {
			 := .Name
			 := .States
			 = append(, jen.Id().Id("S"))
			 := []jen.Code{}
			for ,  := range  {
				 = append(, jen.Id("ss"+).Dot())
			}
			 := []jen.Code{}
			for ,  := range  {
				 = append(, jen.Lit(slices.Index(.Names(), )))
			}
			[jen.Id()] = jen.Id("S").Values(...)
			[jen.Lit()] = jen.Values(...)
			 = append(, jen.Lit())
		}

		// GENERATE
		.Comment("// ///// ///// /////")
		.Line()
		.Comment("// ///// " + strings.ToUpper(spaceCase()))
		.Line()
		.Comment("// ///// ///// /////")
		.Line()

		// type FileStatesDef struct { ... }
		.Comment( + "StatesDef contains states for " +  + ".")
		 = slices.Concat(
			[]jen.Code{jen.Op("*").Qual(, "StatesBase")}, )
		.Type().Id( + "StatesDef").Struct(...)

		.Line()

		// type FileGroupsDef struct { ... }
		.Comment( +
			"GroupsDef contains all the state groups of the " +
			 + " state schema.")
		.Type().Id( + "GroupsDef").Struct(...)

		.Line()

		// var FileSchema = am.Schema{ ... }
		.Comment( +
			"Schema represents all relations and properties of " +
			 + "States.")
		.Var().Id(+"Schema").Op("=").
			Qual(, "Schema").Values()

		.Line()

		// exports
		.Comment("EXPORTS AND GROUPS")
		[jen.Id("StatesBase")] = jen.Op("&").Qual(, "StatesBase").Values(jen.Dict{
			jen.Id("Exception"): jen.Lit("Exception"),
		})
		.Var().Defs(
			jen.Id("ss"+).Op("=").
				Id(+"StatesDef").Values(),
			jen.Id("sg"+).Op("=").
				Id(+"GroupsDef").Values(),
			jen.Line(),
			jen.Comment(+"States contains all the states for the "+
				+" state schema."),
			jen.Id(+"States").Op("=").Id("ss"+),
			jen.Line(),
			jen.Comment(+"Groups contains all the state groups for the "+
				+" state schema."),
			jen.Id(+"Groups").Op("=").Id("sg"+),
		)

		.Line()

		// func init() { ... }
		.Func().Id("init").Params().Block(
			// Note: I preserved your exact string values here, even though
			// they contain "CreatingExpense" etc. from the previous schema instance.
			jen.Id("ss"+).Dot("SetNames").
				Call(jen.Id("S").Values(...)),
			jen.Id("groups").Op(":=").Map(jen.String()).
				Index().Int().Values(),
			jen.Id("ss"+).Dot("SetStateGroups").Call(
				jen.Id("groups"),
				jen.Index().String().Values(...),
			),
		)
	}

	// combine
	return fmt.Sprintf("%#v", )
}

// Group is a state group extracted from a groups struct.
type Group struct {
	Name   string
	States S
}

// ExtractGroups takes any struct and recursively extracts []string fields.
func ( any) map[string]S {
	 := make(map[string]S)

	// Start the recursive extraction
	extract(reflect.ValueOf(), , nil)

	return 
}

// ExtractGroupsOrdered is like ExtractGroups, but preserves the struct
// declaration order (embedded fields first).
func ( any) []Group {
	 := make(map[string]S)
	 := []string{}

	// Start the recursive extraction
	extract(reflect.ValueOf(), , &)

	 := make([]Group, 0, len())
	for ,  := range  {
		 = append(, Group{
			Name:   ,
			States: [],
		})
	}

	return 
}

func extract( reflect.Value,  map[string]S,  *[]string) {
	// 1. Dereference pointers and interfaces to get to the underlying value
	for .Kind() == reflect.Pointer || .Kind() == reflect.Interface {
		if .IsNil() {
			return // Skip nil pointers entirely to avoid panics
		}
		 = .Elem()
	}

	// 2. We only care about traversing structs
	if .Kind() != reflect.Struct {
		return
	}

	 := .Type()

	// 3. Iterate through all fields of the struct
	for  := 0;  < .NumField(); ++ {
		 := .Field()
		 := .Field()

		// Skip unexported fields (lowercase names) as they cannot be accessed
		if !.CanInterface() {
			continue
		}

		// Dereference field if it's a pointer to check its underlying type
		 := 
		for .Kind() == reflect.Pointer ||
			.Kind() == reflect.Interface {
			if .IsNil() {
				break
			}
			 = .Elem()
		}

		if !.IsValid() {
			continue
		}

		// 4. If the field is a struct itself, recurse into it
		if .Kind() == reflect.Struct {
			(, , )
			continue
		}

		// 5. If it's not a struct, check if it is exactly a []string
		if ,  := .Interface().(S);  {
			if ,  := [.Name]; ! &&  != nil {
				* = append(*, .Name)
			}
			[.Name] = 
		}
	}
}

// ///// ///// /////

// ///// HANDLERS

// ///// ///// /////

func ( string) error {
	 := strings.Split(os.Getenv("GOPACKAGE"), "/")
	 := [len()-1] + ".gen.go"
	return os.WriteFile(, []byte(), 0o644)
}

type Handlers struct {
	States   S
	Handlers any
}

type Args struct {
	// Id     string
	// IdRpc  string
	// Val    any
	// ValRpc any
}

func ( string,  *Args,  ...Handlers) string {
	// header

	if  == "" {
		 = os.Getenv("GOPACKAGE")
	}

	 := jen.NewFile()
	.HeaderComment("Code generated by am-gen; DO NOT EDIT.")
	.HeaderComment("//go:build tinygo")

	 := "github.com/pancsta/asyncmachine-go/pkg/machine"
	.ImportAlias(, "am")

	// handlers

	for ,  := range  {

		 := .States

		 := reflect.ValueOf(.Handlers)
		if .Kind() != reflect.Pointer || .Elem().Kind() != reflect.Struct {
			panic("GenHandlers expects a pointer to a struct")
		}

		 := reflect.TypeOf(.Handlers).Elem().Name()
		 := jen.Dict{}
		 := jen.Dict{}
		,  := amhelp.ListHandlers(.Handlers, )
		if  != nil {
			panic()
		}

		for ,  := range  {
			 := strings.HasSuffix(, am.SuffixState) ||
				strings.HasSuffix(, am.SuffixEnd)
			if  {
				[jen.Lit()] = jen.Id("h").Dot()
			} else {
				[jen.Lit()] = jen.Id("h").Dot()
			}
		}

		// func MachineHandlersNegotiations(h *MachineHandlers)
		// map[string]am.HandlerNegotiation { ... }
		.Func().Id(+"Negotiations").
			Params(jen.Id("h").Op("*").Id()).
			Map(jen.String()).Qual(, "HandlerNegotiation").
			Block(
				jen.Return(
					jen.Map(jen.String()).Qual(, "HandlerNegotiation").Values(),
				),
			)

		.Line()

		// func MachineHandlersFinals(h *MachineHandlers)
		// map[string]am.HandlerFinal { ... }
		.Func().Id(+"Finals").
			Params(jen.Id("h").Op("*").Id()).
			Map(jen.String()).Qual(, "HandlerFinal").
			Block(
				jen.Return(
					jen.Map(jen.String()).Qual(, "HandlerFinal").Values(),
				),
			)
	}

	// Output the generated code
	return fmt.Sprintf("%#v", )
}

// ///// ///// /////

// ///// UTILS

// ///// ///// /////

// ExportedFields returns a slice of exported field names for a given struct.
func ( interface{}) []string {
	var  []string

	// 1. Get the type of the interface
	 := reflect.TypeOf()

	// 2. If it's a pointer, dereference it to get the underlying type
	if .Kind() == reflect.Pointer {
		 = .Elem()
	}

	// 3. Make sure we are actually dealing with a struct
	if .Kind() != reflect.Struct {
		return  // Return empty slice if not a struct
	}

	// 4. Iterate over all fields in the struct type
	for  := 0;  < .NumField(); ++ {
		 := .Field()

		// 5. Skip unexported fields (lowercase) because a generated
		// mapper usually can't (and shouldn't) access them.
		if !.IsExported() {
			continue
		}

		 = append(, .Name)
	}

	return 
}

func ( string) string {
	var  strings.Builder

	for ,  := range  {
		if unicode.IsUpper() {
			.WriteRune() // Keep it uppercase
		}
	}

	return .String()
}

var camelCaseRe = regexp.MustCompile(`([a-z0-9])([A-Z])`)

func spaceCase( string) string {
	// Insert a space between lowercase/number and uppercase letters
	 := camelCaseRe.ReplaceAllString(, "$1 $2")

	// Convert the entire result to lowercase
	return strings.ToLower()
}