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) {
	funcName := ctx.FunctionHandler.CurrentFunction()
	ctx.FunctionHandler.EndFunction()
	// Return RTS followed by end marker
	return []string{"\trts", fmt.Sprintf("; @@FUNC_END %s", funcName)}, nil
}
