package generator

// am-gen lint refactors an existing ss_*.go file: it orders the entries of an
// am.Schema literal according to the field order of the matching
// {Name}StatesDef struct and appends empty entries for states which are
// declared in the struct, but missing in the schema.
//
// The refactor works on the original source bytes (go/ast for positions only),
// so formatting and comments are preserved. The result is passed through
// go/format as a safety net.

import (
	
	
	
	goformat 
	
	
	
	

	
)

// LintResult is the outcome of [LintSchemaOrder].
type LintResult struct {
	// Src is the linted source (equal to the input when Changed is false).
	Src []byte
	// Changed is true when Src differs from the input.
	Changed bool
	// Added lists the states which were added to the schema.
	Added []string
	// Reordered is true when existing schema entries changed their order.
	Reordered bool
}

// schemaLit is an am.Schema composite literal along with the name of the var
// it belongs to.
type schemaLit struct {
	lit     *ast.CompositeLit
	varName string
}

// lintEdit is a byte-range replacement within the linted source.
type lintEdit struct {
	start, end int
	repl       string
}

// LintSchemaOrder orders the entries of every am.Schema literal in src
// according to the field order of the matching {Name}StatesDef struct and adds
// entries for missing states. The result is gofmt-ed.
func ( string,  []byte) (*LintResult, error) {
	 := token.NewFileSet()
	,  := parser.ParseFile(, , , parser.ParseComments)
	if  != nil {
		return nil, fmt.Errorf("parse %s: %w", , )
	}

	 := collectStatesDefs()
	 := collectStatesPrefixes(, )
	 := collectSchemaLits()

	var  []lintEdit
	var  []string
	 := false

	for ,  := range  {
		,  := resolveStatesDef(, , )
		if  == "" || len() == 0 {
			// no matching StatesDef (e.g. a bare schema without a struct)
			continue
		}

		, , , ,  := lintSchemaLit(
			, , , , , )
		if  != nil {
			return nil, fmt.Errorf("%s: %w", , )
		}
		if ! {
			continue
		}

		 = append(, )
		 = append(, ...)
		 =  || 
	}

	if len() == 0 {
		return &LintResult{Src: }, nil
	}

	// apply from the end, so earlier offsets stay valid
	sort.Slice(, func(,  int) bool {
		return [].start > [].start
	})
	 := 
	for ,  := range  {
		 = spliceBytes(, .start, .end, .repl)
	}

	,  := goformat.Source()
	if  != nil {
		return nil, fmt.Errorf("format %s: %w", , )
	}

	 := &LintResult{
		Src:       ,
		Added:     ,
		Reordered: ,
	}
	.Changed = !bytes.Equal(, )
	if !.Changed {
		.Src = 
		.Added = nil
		.Reordered = false
	}

	return , nil
}

// lintSchemaLit lints a single am.Schema literal. ok is false when the literal
// cannot be processed (e.g. unexpected keys) and should be left untouched.
func lintSchemaLit(
	 *token.FileSet,  []byte,  schemaLit,  string,
	 []string,  map[string]string,
) ( lintEdit,  []string, ,  bool,  error) {
	 := .lit
	 := func( token.Pos) int { return .Position().Offset }
	 := litPrefix()
	if  == "" {
		 = fallbackStatesPrefix(, )
	}

	 := (.Lbrace) + 1
	 := (.Rbrace)

	// no entries yet: generate all of them
	if len(.Elts) == 0 {
		 := lineIndent(, (.Lbrace))
		 :=  + "\t"
		var  []string
		for ,  := range  {
			 = append(, ++"."++": {},")
			 = append(, )
		}
		if len() == 0 {
			return , nil, false, false, nil
		}
		 := "\n" + strings.Join(, "\n") + "\n" + 
		return lintEdit{start: , end: , repl: },
			, false, true, nil
	}

	// single line (or a closing brace sharing the line with the last entry):
	// rebuild compactly, comments inside such a literal are not supported
	 := .Position(.Elts[len(.Elts)-1].End()).Line
	if .Position(.Lbrace).Line == .Position(.Rbrace).Line ||
		 == .Position(.Rbrace).Line {
		return lintSchemaLitCompact(, , , , )
	}

	type  struct {
		       string
		        string
		       int
		 bool
	}
	 := func( string) int {
		for ,  := range  {
			if  ==  {
				return 
			}
		}
		return -1
	}

	var  []
	// gaps[i] is the text before block i, gaps[len(blocks)] is the text
	// between the last block and the closing brace
	var  []string
	 := 

	for ,  := range .Elts {
		,  := .(*ast.KeyValueExpr)
		if ! {
			return , nil, false, false, nil
		}
		,  := .Key.(*ast.SelectorExpr)
		if ! {
			return , nil, false, false, nil
		}
		 := .Sel

		 := attachCommentStart(, (.Pos()))
		 := lineEndOffset(, (.End()))
		if  >  {
			 = 
		}
		var  string
		if  == 0 {
			 = string([:])
		} else {
			 = string([:])
		}
		 = append(, )
		 = append(, {
			:       .Name,
			:        string([:]),
			:       (.Name),
			: strings.Contains(, "\n\n"),
		})
		 = 
	}
	 = append(, string([:]))

	// add missing states
	 := make(map[string]bool, len())
	for ,  := range  {
		[.] = true
	}
	 := leadingWhitespace([0].)
	if  == "" {
		 = lineIndent(, (.Lbrace)) + "\t"
	}
	for ,  := range  {
		if [] {
			continue
		}
		 = append(, {
			: ,
			:   +  + "." +  + ": {},",
			: (),
		})
		 = append(, )
	}

	// stable sort: unknown states (e.g. overridden inherited ones) float to
	// the top in their original order
	 := make([], len())
	copy(, )
	sort.SliceStable(, func(,  int) bool {
		return []. < [].
	})
	for  := range  {
		if []. != []. {
			 = true
			break
		}
	}

	// blank lines travel with their entries, comment paragraphs always get one
	 := [0]
	 := [len()-1]
	var  strings.Builder
	for ,  := range  {
		 := "\n"
		if . ||
			strings.HasPrefix(strings.TrimLeft(., " \t"), "//") {
			 = "\n\n"
		}
		if  == 0 {
			 = 
		}
		.WriteString()
		.WriteString(.)
	}
	.WriteString()

	return lintEdit{start: , end: , repl: .String()},
		, , true, nil
}

// lintSchemaLitCompact rebuilds a single-line schema literal.
func lintSchemaLitCompact(
	 *token.FileSet,  []byte,  schemaLit,  []string,
	 string,
) ( lintEdit,  []string, ,  bool,  error) {
	 := .lit
	 := func( token.Pos) int { return .Position().Offset }

	type  struct {
		 string
		   string
		 string
		 int
	}
	 := func( string) int {
		for ,  := range  {
			if  ==  {
				return 
			}
		}
		return -1
	}

	var  []
	for ,  := range .Elts {
		,  := .(*ast.KeyValueExpr)
		if ! {
			return , nil, false, false, nil
		}
		,  := .Key.(*ast.SelectorExpr)
		if ! {
			return , nil, false, false, nil
		}
		 := .Sel
		 = append(, {
			: .Name,
			:   string([(.Key.Pos()):(.Key.End())]),
			: string([(.Value.Pos()):(.Value.End())]),
			: (.Name),
		})
	}

	 := make(map[string]bool, len())
	for ,  := range  {
		[.] = true
	}
	for ,  := range  {
		if [] {
			continue
		}
		 = append(, {
			: ,
			:    + "." + ,
			: "{}",
			: (),
		})
		 = append(, )
	}

	 := make([], len())
	copy(, )
	sort.SliceStable(, func(,  int) bool {
		return []. < [].
	})
	for  := range  {
		if []. != []. {
			 = true
			break
		}
	}

	var  []string
	for ,  := range  {
		 = append(, .+": "+.)
	}
	// the replacement covers the inside of the braces only
	 := strings.Join(, ", ")

	return lintEdit{
			start: (.Lbrace) + 1,
			end:   (.Rbrace),
			repl:  ,
		},
		, , true, nil
}

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

// ///// AST

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

// collectStatesDefs returns the ordered string fields of all {Name}StatesDef
// structs in the file, indexed by the struct name.
func collectStatesDefs( *ast.File) map[string][]string {
	 := make(map[string][]string)
	for ,  := range .Decls {
		,  := .(*ast.GenDecl)
		if ! || .Tok != token.TYPE {
			continue
		}
		for ,  := range .Specs {
			,  := .(*ast.TypeSpec)
			if ! || !strings.HasSuffix(.Name.Name, "StatesDef") {
				continue
			}
			,  := .Type.(*ast.StructType)
			if ! {
				continue
			}
			var  []string
			for ,  := range .Fields.List {
				// skip embedded structs
				if len(.Names) == 0 {
					continue
				}
				if ,  := .Type.(*ast.Ident); ! || .Name != "string" {
					continue
				}
				for ,  := range .Names {
					 = append(, .Name)
				}
			}
			[.Name.Name] = 
		}
	}
	return 
}

// collectStatesPrefixes maps states var names (eg ssM) to StatesDef names, by
// looking for {Name}StatesDef{} passed to am.NewStates.
func collectStatesPrefixes(
	 *ast.File,  map[string][]string,
) map[string]string {
	 := make(map[string]string)
	for ,  := range .Decls {
		,  := .(*ast.GenDecl)
		if ! || .Tok != token.VAR {
			continue
		}
		for ,  := range .Specs {
			,  := .(*ast.ValueSpec)
			if ! || len(.Names) != 1 || len(.Values) != 1 {
				continue
			}
			,  := .Values[0].(*ast.CallExpr)
			if ! {
				continue
			}
			,  := .Fun.(*ast.SelectorExpr)
			if ! || .Sel.Name != "NewStates" || len(.Args) != 1 {
				continue
			}
			 := compositeTypeName(.Args[0])
			if ,  := []; ! {
				continue
			}
			[.Names[0].Name] = 
		}
	}
	return 
}

// collectSchemaLits returns all am.Schema literals which are values of a var,
// skipping the receiver of am.Schema{}.Merge(...).
func collectSchemaLits( *ast.File) []schemaLit {
	 := make(map[*ast.CompositeLit]string)
	for ,  := range .Decls {
		,  := .(*ast.GenDecl)
		if ! || .Tok != token.VAR {
			continue
		}
		for ,  := range .Specs {
			,  := .(*ast.ValueSpec)
			if ! {
				continue
			}
			 := ""
			if len(.Names) > 0 {
				 = .Names[0].Name
			}
			for ,  := range .Values {
				ast.Inspect(, func( ast.Node) bool {
					if ,  := .(*ast.CompositeLit);  && isAmSchemaLit() {
						[] = 
					}
					return true
				})
			}
		}
	}

	var  []schemaLit
	astutil.Apply(, func( *astutil.Cursor) bool {
		,  := .Node().(*ast.CompositeLit)
		if ! || !isAmSchemaLit() {
			return true
		}
		// skip the am.Schema{}.Merge(...) receiver
		if ,  := .Parent().(*ast.SelectorExpr);  && .X ==  {
			return true
		}
		,  := []
		if ! {
			return true
		}
		 = append(, schemaLit{lit: , varName: })
		return true
	}, nil)

	return 
}

// resolveStatesDef finds the {Name}StatesDef matching a schema literal.
func resolveStatesDef(
	 schemaLit,  map[string][]string,  map[string]string,
) (string, []string) {
	 := ""
	// by the states var prefix (eg ssM)
	if  := litPrefix(.lit);  != "" {
		 = []
	}
	// by the schema var name (eg MyMachSchema -> MyMachStatesDef)
	if  == "" && strings.HasSuffix(.varName, "Schema") {
		 := strings.TrimSuffix(.varName, "Schema") + "StatesDef"
		if ,  := [];  {
			 = 
		}
	}
	// fall back to the only StatesDef in the file
	if  == "" && len() == 1 {
		for  := range  {
			 = 
		}
	}
	if  == "" {
		return "", nil
	}
	return , []
}

// litPrefix returns the package-level var prefix of schema entries (eg ssM in
// ssM.Start).
func litPrefix( *ast.CompositeLit) string {
	for ,  := range .Elts {
		,  := .(*ast.KeyValueExpr)
		if ! {
			continue
		}
		,  := .Key.(*ast.SelectorExpr)
		if ! {
			continue
		}
		,  := .X.(*ast.Ident)
		if ! {
			continue
		}
		return .Name
	}
	return ""
}

// fallbackStatesPrefix derives the states var name for an empty schema literal.
func fallbackStatesPrefix( string,  map[string]string) string {
	for ,  := range  {
		if  ==  {
			return 
		}
	}
	 := strings.TrimSuffix(, "StatesDef")
	if  == "" {
		return "ss"
	}
	return "ss" + strings.ToUpper([:1])
}

func isAmSchemaLit( *ast.CompositeLit) bool {
	,  := .Type.(*ast.SelectorExpr)
	if ! {
		return false
	}
	,  := .X.(*ast.Ident)
	return  && .Name == "am" && .Sel.Name == "Schema"
}

func compositeTypeName( ast.Expr) string {
	switch t := .(type) {
	case *ast.CompositeLit:
		if ,  := .Type.(*ast.Ident);  {
			return .Name
		}
	case *ast.UnaryExpr:
		return (.X)
	case *ast.ParenExpr:
		return (.X)
	}
	return ""
}

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

// ///// SOURCE

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

// attachCommentStart walks up from the entry line over blank lines and
// contiguous // comments, returning the start of the attached comment
// paragraph (or the entry line when there is none).
func attachCommentStart( []byte,  int) int {
	 := lineStartOffset(, )
	 := 
	for  > 0 {
		 :=  - 1
		 := lineStartOffset(, )
		 := strings.TrimSpace(string([:]))
		if  == "" {
			 = 
			continue
		}
		if !strings.HasPrefix(, "//") {
			break
		}
		 = 
		 = 
	}
	return 
}

func lineStartOffset( []byte,  int) int {
	if  > len() {
		 = len()
	}
	for  > 0 && [-1] != '\n' {
		--
	}
	return 
}

func lineEndOffset( []byte,  int) int {
	if  > len() {
		 = len()
	}
	for  < len() && [] != '\n' {
		++
	}
	return 
}

// lineIndent returns the leading whitespace of the line containing off.
func lineIndent( []byte,  int) string {
	 := lineStartOffset(, )
	 := 
	for  < len() && ([] == ' ' || [] == '\t') {
		++
	}
	return string([:])
}

func leadingWhitespace( string) string {
	 := 0
	for  < len() && ([] == ' ' || [] == '\t') {
		++
	}
	return [:]
}

func spliceBytes( []byte, ,  int,  string) []byte {
	 := make([]byte, 0, len()-(-)+len())
	 = append(, [:]...)
	 = append(, ...)
	 = append(, [:]...)
	return 
}