package commands

import (
	"fmt"
	"strings"

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

// ElseCommand handles ELSE statements
// Syntax: ELSE
// Marks alternative branch in IF...ELSE...ENDIF
type ElseCommand struct {
	skipLabel  string
	endifLabel string
}

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

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

	// Pop skip label (where IF jumps on FALSE)
	var err2 error
	c.skipLabel, err2 = ctx.IfStack.Pop()
	if err2 != nil {
		return fmt.Errorf("ELSE: not inside IF block")
	}

	// Push new endif label (where to jump after IF block)
	c.endifLabel = ctx.IfStack.Push()

	return nil
}

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

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