package router

import (
	"github.com/kami/maven/internal/lexicon"
	"github.com/kami/maven/internal/morph"
)

// ReminderCancellationReportGrammar keeps a completed-action statement out of
// recall. The mutation lane accepts only an imperative at the start of the
// turn; "я отменил напоминание" is instead a first-person report and must not
// be reinterpreted as either a cancellation request or a memory question.
func ReminderCancellationReportGrammar() Grammar {
	return Grammar{Name: "reminder-cancellation-report", Decide: reminderCancellationReportDecision}
}

func reminderCancellationReportDecision(utterance string) (Decision, bool) {
	if IsQuestionShaped(utterance) || CarriesCaptureVerb(utterance) {
		return Decision{}, false
	}
	tokens := planTokens(utterance)
	i := 0
	for i < len(tokens) && lexicon.IsFillerParticle(tokens[i]) {
		i++
	}
	if i >= len(tokens) || (tokens[i] != "я" && tokens[i] != "i") {
		return Decision{}, false
	}
	i++
	firstVerb := ""
	for ; i < len(tokens); i++ {
		if morph.IsVerbForm(tokens[i]) || hasExactWord(lexicon.ReminderCancelReportVerbs(), tokens[i]) {
			firstVerb = tokens[i]
			break
		}
	}
	if firstVerb == "" || !sameAsAny(firstVerb, lexicon.ReminderCancelReportVerbs()) {
		return Decision{}, false
	}
	hasReminder := false
	for _, token := range tokens {
		if sameAsAny(token, lexicon.ReminderNouns()) {
			hasReminder = true
			break
		}
	}
	if !hasReminder {
		return Decision{}, false
	}
	return Decision{
		Stage:      0,
		Intent:     IntentChat,
		Confidence: 1,
		Slots:      Slots{Text: utterance},
	}, true
}

func sameAsAny(token string, forms []string) bool {
	for _, form := range forms {
		if token == form || morph.SameWord(token, form) {
			return true
		}
	}
	return false
}
