package main

import (
	"context"
	"strings"
	"testing"
	"time"

	"github.com/kami/maven/internal/router"
)

func TestIsAttentionQuery(t *testing.T) {
	for _, tc := range []struct {
		text string
		want bool
	}{
		{"что требует внимания", true},
		{"на что обратить внимание?", true},
		{"что не так?", true},
		{"что важного?", true},
		// The feeds source owns this one, and should keep owning it.
		{"что нового?", false},
		{"какая погода?", false},
		{"", false},
	} {
		if got := isAttentionQuery(tc.text); got != tc.want {
			t.Errorf("isAttentionQuery(%q) = %v, want %v", tc.text, got, tc.want)
		}
	}
}

// TestAttentionQuestionReachesPraxis — the defect (Vikunja #475). The question
// routes to IntentQuery, and every source used to pass, so a web search about
// the concept of attention answered it.
func TestAttentionQuestionReachesPraxis(t *testing.T) {
	ctx := context.Background()
	praxis := newFakePraxis(t, fixturePraxisAttentionItems(map[string]any{
		"id": "item_1", "title": "disk almost full", "importance": 3.0,
	}))
	h := ecoHandler(t, nil, praxis, nil)

	reply, ok := h.queryAttention(ctx, &queryTurn{dec: router.Decision{
		Intent: router.IntentQuery, Utterance: "что требует внимания",
	}})
	if !ok {
		t.Fatal("the attention question must be claimed before the world sources")
	}
	if !strings.Contains(reply, "disk almost full") {
		t.Fatalf("reply = %q, want the praxis item", reply)
	}
}

// A configured Praxis that is down claims the turn and says so. Falling
// through here would answer an outage with an encyclopedia article.
func TestAttentionQuestionSaysWhenPraxisIsDown(t *testing.T) {
	ctx := context.Background()
	praxis := newFakePraxis(t, fixturePraxisAttentionItems())
	h := ecoHandler(t, nil, praxis, nil)
	praxis.SetFault(503)

	reply, ok := h.queryAttention(ctx, &queryTurn{dec: router.Decision{
		Intent: router.IntentQuery, Utterance: "что требует внимания",
	}})
	if !ok || !strings.Contains(reply, "не могу") {
		t.Fatalf("an outage must name the gap, got ok=%v reply=%q", ok, reply)
	}
}

// No Praxis configured means no claim: the rest of the chain still runs.
func TestAttentionQuestionFallsThroughWithoutPraxis(t *testing.T) {
	h, _ := newFactGateHandler(t, time.Now())
	if _, ok := h.queryAttention(context.Background(), &queryTurn{dec: router.Decision{
		Intent: router.IntentQuery, Utterance: "что требует внимания",
	}}); ok {
		t.Fatal("an unconfigured praxis must not claim the turn")
	}
}
