package machine

import (
	
	
	
	
	
)

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

// ///// STATES

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

// StatesBase is the base class for schema states definition, providing compiler
// safety and holding order of state names, as well as groups.
type StatesBase struct {
	// TODO rename to SchemaStates

	// TODO Prefix, support prefixing index and struct field vals

	// Exception is the only built-in state and mean a global error. All errors
	// have to [State.Require] the Exception state. If [Machine.PanicToErr] is
	// true, Exception will receive it.
	Exception   string
	names       S
	groups      map[string][]int
	groupsOrder []string
	// prefix for nesting
	prefix string
}

var _ States = &StatesBase{}

// Prefix returns the nesting prefix for this state definition.
func ( *StatesBase) () string {
	return .prefix
}

func ( *StatesBase) () S {
	return .names
}

func ( *StatesBase) () (map[string][]int, []string) {
	return .groups, .groupsOrder
}

func ( *StatesBase) ( S) {
	.names = slicesUniq()
}

func ( *StatesBase) ( map[string][]int,  []string) {
	.groups = 
	.groupsOrder = 
}

// States is the vase interface for schema states. TODO name to SchemaStates?
type States interface {
	// Names returns the state names of the state machine.
	Names() S
	StateGroups() (map[string][]int, []string)
	SetNames(S)
	SetStateGroups(map[string][]int, []string)
}

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

// ///// SCHEMA

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

// Schema is a map of state names to state definitions.
type Schema map[string]State

// Merge merges multiple state structs into one, overriding the previous
// state definitions. No relation-level merging takes place.
func ( Schema) ( ...Schema) Schema {
	// TODO mark all-but-last states as Inherited?
	// TODO example
	// TODO test
	// defaults
	 := len()
	switch  {
	case 0:
		return 
	}

	 := .Clone()
	for  := 0;  < ; ++ {
		maps.Copy(, [])
	}

	// rm noname states
	delete(, "")

	return .Clone()
}

// Prefix will prefix all state names with [prefix]. skipPrefixed will skip
// overlaps eg "FooFooName" will remain "FooName".
func ( Schema) (
	 string,  bool, ,  S,
) Schema {
	 := Schema{}
	for ,  := range  {
		 = .Clone()

		if len() > 0 && !slices.Contains(, ) {
			continue
		} else if len() > 0 && slices.Contains(, ) {
			continue
		}

		for ,  := range .After {
			 := 
			if ! || !strings.HasPrefix(, ) {
				 =  + 
			}
			.After[] = 
		}
		for ,  := range .Add {
			 := 
			if ! || !strings.HasPrefix(, ) {
				 =  + 
			}
			.Add[] = 
		}
		for ,  := range .Remove {
			 := 
			if ! || !strings.HasPrefix(, ) {
				 =  + 
			}
			.Remove[] = 
		}
		for ,  := range .Require {
			 := 
			if ! || !strings.HasPrefix(, ) {
				 =  + 
			}
			.Require[] = 
		}

		 := 
		if ! || !strings.HasPrefix(, ) {
			 =  + 
		}

		// build
		[] = 
	}

	return 
}

// Clone deep clones the states struct and returns a copy.
func ( Schema) () Schema {
	 := make(Schema)

	for ,  := range  {
		[] = .Clone()
	}

	return 
}

// Parse sanitizes the schema and returns potential errors.
func ( Schema) () (Schema, error) {
	// TODO capitalize states
	// TODO ErrFoo must require Exception

	 := .Clone()
	 := slices.Collect(maps.Keys())
	var  error
	for ,  := range  {

		// avoid self removal
		if slices.Contains(.Remove, ) {
			.Remove = slicesWithout(.Remove, )
		}

		// don't Remove if in Add
		for ,  := range .Add {
			if slices.Contains(.Remove, ) {
				.Remove = slicesWithout(.Remove, )

				// check if exists
			} else if !slices.Contains(, ) {
				.Add = slicesWithout(.Add, )
			}
		}

		// avoid being after itself
		if slices.Contains(.After, ) {
			.After = slicesWithout(.After, )
		}

		// detect require-remove conflicts
		for ,  := range .Require {
			if slices.Contains(.Remove, ) {
				 = errors.Join(, errorf(
					"%w: require-remove conflict for %s to %s",
					ErrSchema, , ,
				))
			}
		}

		// remove references to non-existing states
		for ,  := range .Remove {
			if !slices.Contains(, ) {
				.Remove = slicesWithout(.Remove, )
			}
		}
		for ,  := range .After {
			if !slices.Contains(, ) {
				.After = slicesWithout(.After, )
			}
		}
		for ,  := range .Remove {
			if !slices.Contains(, ) {
				.Remove = slicesWithout(.Remove, )
			}
		}

		[] = 
	}

	return , 
}

// FilterByTag returns a subset schema with states having the given tag.
func ( Schema) ( string) Schema {
	 := Schema{}
	for ,  := range  {
		if slices.Contains(.Tags, ) {
			[] = 
		}
	}

	return 
}

// FilterByTagKey returns a subset schema with states having a value tag
// prefixed with [key].
func ( Schema) ( string) Schema {
	 := Schema{}
	for ,  := range  {
		for ,  := range .Tags {
			if strings.HasPrefix(, +":") {
				[] = 
				break
			}
		}
	}

	return 
}

// Names is a random-order list of defined state names.
func ( Schema) () S {
	return slices.Collect(maps.Keys())
}

func ( Schema) ( string) S {
	if ,  := []; ! {
		return nil
	}
	 := []

	return slices.Concat(.Add, .After, .Require, .Remove)
}

func ( Schema) ( string,  S) Schema {
	 := Schema{}

	for ,  := range  {
		 := []
		.Require = prefixRels(, , .Require)
		.Add = prefixRels(, , .Add)
		.Remove = prefixRels(, , .Remove)
		.After = prefixRels(, , .After)
		[+] = 
	}

	return 
}

// Get a map index with a default ret value.
func ( Schema) ( string) State {
	,  := []
	if ! {
		return State{}
	}
	return 
}

func ( Schema) ( Schema) bool {
	return .Names().HasN(.Names())
}

func ( Schema) ( S) bool {
	return .Names().HasN()
}

func prefixRels( string, ,  S) S {
	if  == nil {
		return nil
	}
	 := make(S, len())
	for ,  := range  {
		// prefix only the states from this schema
		if !slices.Contains(, ) {
			[] = 
			continue
		}

		[] =  + 
	}

	return 
}

// ----- old

// SchemaMerge is deprecated, use [Schema.Merge].
func ( ...Schema) Schema {
	 := len()
	switch  {
	case 0:
		return Schema{}
	case 1:
		return [0]
	}

	 := make(Schema)
	for  := 0;  < ; ++ {
		// TODO clone?
		maps.Copy(, [])
	}

	return .Clone()
}

// StatesByTag is deprecated, use
//
//	Schema.FilterByTag("").Names()
func ( Schema,  string) S {
	 := S{}
	for ,  := range  {
		for ,  := range .Tags {
			if  ==  || strings.HasPrefix(, +":") {
				 = append(, )
				break
			}
		}
	}

	return 
}

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

// ///// ARGS

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

const APrefix = "_am"

// ArgsApi is the base interface for typed arguments.
type ArgsApi interface {
	// ArgsPrefix returns the argument prefix inside the [A] map. Should be
	// provided by the implementation.
	ArgsPrefix() string
	// ArgsState represents the state this argument struct belongs to.
	// Defaults to [StateAny].
	ArgsState() string

	// TODO enable in v0.20
	// ArgsPrefixNested returns both args prefix and the optional nesting prefix.
	// ArgsPrefixNested() string
	// TODO deep clone interface, optional
	// ArgsClone() G
}

// ArgsBase is the base implementation of [ArgsApi] interface.
type ArgsBase struct {
	ArgsApi
	// TODO enable in v0.20
	// prefixNested string
}

// TODO enable in v0.20
// func (a ArgsBase) Nest(nested string) ArgsBase {
// 	a.prefixNested = nested
// 	return a
// }

// TODO enable in v0.20
// func (a ArgsBase) PrefixNested() string {
// 	return a.ArgsState() + a.prefixNested
// }

// ArgsPrefix is a fallback to a stack trace hash of the implementation
// symbol. Each pkg should overwrite this method.
func ( ArgsBase) () string {
	 := make([]byte, 4024)
	 := runtime.Stack(, false)
	 := string([:])
	 := strings.Split(, "\n")
	if len() < 4 {
		// tinygo's runtime.Stack is a no-op, use a stable fallback
		return Hash("tinygo", 10)
	}
	 := Hash([3], 10)

	return 
}

// ArgsState is the default Any state.
func ( ArgsBase) () string {
	return StateAny
}

// Clone for deep cloning.
func ( ArgsBase) () ArgsApi {
	// shallow clone
	return 
}

// pkg args

// Args for this pkg. Do not reuse.
type Args struct {
	ArgsBase
}

func (Args) () string {
	return APrefix
}

// -----

// ExceptionArgsPanic is an optional argument ["panic"] for the StateException
// state which describes a panic within a Transition handler.
type ExceptionArgsPanic struct {
	CalledStates S
	StatesBefore S
	Transition   *Transition
	LastStep     *Step
	StackTrace   string
}

type AException struct {
	Args
	Err      error `log:"err"`
	ErrTrace string
	Panic    *ExceptionArgsPanic

	// TODO handle
	Fn string `log:"fn"`

	// deadline

	TargetStates S
	CalledStates S
	TimeBefore   Time
	TimeAfter    Time
	Event        *Event
}

func (AException) () string {
	return StateException
}

// ACheck with a CheckDone chan which gets closed by the machine once it's
// processed. Can cause chan leaks when misused. Only for Can* checks.
type ACheck struct {
	Args
	// TODO close these on dispose and deadline
	// TODO optimize: poll atomics instead of alloc chans (bench first)
	CheckDone chan struct{}
	// Was the mutation canceled?
	Canceled bool
}

// -----

// PassMerge merged one or more [A] into [A]. Technically a `map[string]any`
// merge.
func ( ...A) A {
	 := A{}
	for ,  := range  {
		for ,  := range  {
			[] = 
		}
	}

	return 
}

// Pass accepts pointers of [ArgsBase] to pass to the machine as [A].
func ( ...ArgsApi) A {
	 := A{}
	for ,  := range  {
		[ArgIndex()] = 
	}

	return 
}

// ParseArgs is [ParseArgsCheck] but without the check.
func [ ArgsApi]( A) * {
	,  := ParseArgsCheck[]()
	return 
}

// ParseArgsCheck parses [A] into typed arguments described by the
// passed generic
// type. Returns
func [ ArgsApi]( A) (*, bool) {
	var  
	 := ArgIndex()
	,  := [].(*)
	if ! {
		// RPC support
		,  := [].()
		if ! {
			// fallback
			return &, false
		}
		 = &
	}

	return , true
}

// ArgIndex return an index of [arg] inside [A].
func ( ArgsApi) string {
	// TODO arg.ArgsPrefixNested()
	 := .ArgsPrefix()
	 := .ArgsState()
	return  + "__" + 
}

// TODO
// func (e *Event) ArgsState(state string, def any) any {
// }