package commands

import (
	"fmt"
	"strings"

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

// WendCommand handles WEND statements
// Syntax: WEND
// Ends current WHILE loop
type WendCommand struct {
	loopLabel string
	skipLabel string
}

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

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

	if len(params) != 1 {
		return fmt.Errorf("WEND: expected 1 parameter, got %d", len(params))
	}

	// Pop loop label
	var err2 error
	c.loopLabel, err2 = ctx.LoopStartStack.Pop()
	if err2 != nil {
		return fmt.Errorf("WEND: not inside WHILE loop")
	}

	// Pop skip label
	c.skipLabel, err2 = ctx.LoopEndStack.Pop()
	if err2 != nil {
		return fmt.Errorf("WEND: not inside WHILE loop")
	}

	return nil
}

func (c *WendCommand) Generate(_ *compiler.CompilerContext) ([]string, error) {
	return []string{
		fmt.Sprintf("\tjmp %s", c.loopLabel),
		c.skipLabel,
	}, nil
}

func (c *WendCommand) GetClass() compiler.CmdClass { return compiler.CmdFlowCtrl }
func (c *WendCommand) GetName() string              { return "WEND" }
