package knowledge

import "testing"

func TestUniqueSourceCount(t *testing.T) {
	count := uniqueSourceCount([]BraveSource{
		{URL: "https://a.example"},
		{URL: "https://a.example"},
		{URL: "https://b.example"},
		{URL: ""},
	})
	if count != 2 {
		t.Fatalf("expected 2 unique urls, got %d", count)
	}
}

func TestPlanQueriesHybridBudget(t *testing.T) {
	queries := PlanQueries(PlanInput{
		Seed:           "敏感肌",
		TargetAudience: "孕婦",
		Questions:      []string{"q1", "q2", "q3", "q4"},
		Pillars:        []string{"p1", "p2", "p3"},
		L1Labels:       []string{"a", "b", "c", "d"},
		Strategy:       ExpandStrategyHybrid,
	})
	if len(queries) > 4 {
		t.Fatalf("hybrid should cap at 4 queries, got %d: %v", len(queries), queries)
	}
	if len(queries) == 0 {
		t.Fatal("expected some queries")
	}
}

func TestPlanQueriesPrioritizesPatrolKeywords(t *testing.T) {
	queries := PlanQueries(PlanInput{
		Seed:           "敏感肌",
		PatrolKeywords: []string{"化療 沐浴乳", "無香沐浴乳 推薦"},
		Questions:      []string{"很長的受眾提問一", "很長的受眾提問二"},
		Strategy:       ExpandStrategyBrave,
	})
	if len(queries) == 0 {
		t.Fatal("expected queries")
	}
	if queries[0] != "化療 沐浴乳" {
		t.Fatalf("expected patrol keyword first, got %q", queries[0])
	}
}

func TestQueriesExcept(t *testing.T) {
	remaining := QueriesExcept(
		[]string{"a", "b", "c", "d"},
		[]string{"a", "c"},
	)
	if len(remaining) != 2 || remaining[0] != "b" || remaining[1] != "d" {
		t.Fatalf("unexpected remaining: %v", remaining)
	}
}

func TestPlanBootstrapQueriesSkipsResearchMapFields(t *testing.T) {
	full := PlanQueries(PlanInput{
		Seed:      "敏感肌",
		Questions: []string{"q1"},
		Pillars:   []string{"p1"},
		Strategy:  ExpandStrategyBrave,
	})
	bootstrap := PlanBootstrapQueries(PlanInput{
		Seed:      "敏感肌",
		Questions: []string{"q1"},
		Pillars:   []string{"p1"},
		Strategy:  ExpandStrategyBrave,
	})
	if len(bootstrap) == 0 {
		t.Fatal("expected bootstrap queries")
	}
	for _, q := range bootstrap {
		if q == "q1" || q == "p1 請問" {
			t.Fatalf("bootstrap should not include research map query %q", q)
		}
	}
	if len(full) <= len(bootstrap) {
		t.Fatalf("full plan should include more queries than bootstrap: full=%v bootstrap=%v", full, bootstrap)
	}
}

func TestMergeBraveSourcesDedupesURLs(t *testing.T) {
	merged := MergeBraveSources(
		[]BraveSource{{URL: "https://a.example", Query: "q1"}},
		[]BraveSource{{URL: "https://a.example", Query: "q2"}, {URL: "https://b.example", Query: "q3"}},
	)
	if len(merged) != 2 {
		t.Fatalf("expected 2 merged sources, got %d", len(merged))
	}
}

func TestSupplementalQueriesSkippedForHybrid(t *testing.T) {
	queries := PlanQueries(PlanInput{
		Seed:         "敏感肌",
		Supplemental: true,
		Strategy:     ExpandStrategyHybrid,
	})
	if len(queries) != 0 {
		t.Fatalf("hybrid supplemental brave should be empty, got %v", queries)
	}
}
