package commands

import (
	"fmt"
	"strings"

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

// LabelCommand handles LABEL declarations
// Syntax: LABEL name
// Emits an assembly label for GOTO/GOSUB/CALL to target
type LabelCommand struct {
	labelName string
}

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

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

	if len(params) != 2 {
		return fmt.Errorf("LABEL: expected 2 parameters, got %d", len(params))
	}

	c.labelName = params[1]

	if len(c.labelName) < 2 {
		return fmt.Errorf("LABEL: label name must be at least 2 characters long")
	}

	return nil
}

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

func (c *LabelCommand) GetClass() compiler.CmdClass { return compiler.CmdBoundary }
func (c *LabelCommand) GetName() string              { return "LABEL" }
