package commands

import (
	"fmt"
	"strings"

	"c65gm/internal/compiler"
	"c65gm/internal/preproc"
	"c65gm/internal/utils"
)

// FendCommand handles FEND (function end)
// Syntax:
//
//	FEND
type FendCommand struct {
}

func (c *FendCommand) WillHandle(line preproc.Line) bool {
	params, err := utils.ParseParams(line.Text)
	if err != nil || len(params) == 0 {
		return false
	}
	return strings.ToUpper(params[0]) == "FEND"
}

func (c *FendCommand) Interpret(line preproc.Line, _ *compiler.CompilerContext) error {
	params, err := utils.ParseParams(line.Text)
	if err != nil {
		return err
	}

	if len(params) != 1 {
		return fmt.Errorf("FEND: no parameters expected, got %d", len(params)-1)
	}

	return nil
}

func (c *FendCommand) Generate(ctx *compiler.CompilerContext) ([]string, error) {
	funcNames := ctx.FunctionHandler.GetCurrentFunctions()
	ctx.FunctionHandler.EndFunction()
	// Return RTS followed by end markers for all functions in the group
	lines := []string{"\trts"}
	for _, name := range funcNames {
		lines = append(lines, fmt.Sprintf("; @@FUNC_END %s", name))
	}
	return lines, nil
}

func (c *FendCommand) GetClass() compiler.CmdClass { return compiler.CmdBoundary }
func (c *FendCommand) GetName() string              { return "FEND" }
