package commands

import (
	"fmt"
	"strings"

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

// SubEndCommand handles SUBEND/EXIT statements
// Syntax: SUBEND (no parameters)
//
//	EXIT   (no parameters)
//
// Generates RTS (return from subroutine)
type SubEndCommand struct{}

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

func (c *SubEndCommand) 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("SUBEND: no parameters allowed")
	}

	return nil
}

func (c *SubEndCommand) Generate(_ *compiler.CompilerContext) ([]string, error) {
	return []string{"\trts"}, nil
}

func (c *SubEndCommand) GetClass() compiler.CmdClass { return compiler.CmdLinear }
func (c *SubEndCommand) GetName() string              { return "SUBEND" }
