package commands

import (
	"fmt"
	"strings"

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

// EndIfCommand handles ENDIF statements
// Syntax: ENDIF
// Ends current IF block
type EndIfCommand struct {
	endLabel string
}

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

func (c *EndIfCommand) 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("ENDIF: expected 1 parameter, got %d", len(params))
	}

	// Pop end label
	var err2 error
	c.endLabel, err2 = ctx.IfStack.Pop()
	if err2 != nil {
		return fmt.Errorf("ENDIF: not inside IF block")
	}

	return nil
}

func (c *EndIfCommand) Generate(_ *compiler.CompilerContext) ([]string, error) {
	return []string{c.endLabel}, nil
}

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