package recommend

import (
	"testing"
	"time"
)

func TestContextAffinityPrefersTypicalWeekdayTime(t *testing.T) {
	location := time.FixedZone("test", 12*60*60)
	profile := NewContextAffinityProfile()
	comedy := Item{Genres: []string{"Comedy"}}
	drama := Item{Genres: []string{"Drama"}}
	for i := 0; i < 6; i++ {
		profile.Add(
			comedy,
			time.Date(2026, 7, 6+i*7, 19, 30, 0, 0, location),
			1,
			i,
			location,
		)
		profile.Add(
			drama,
			time.Date(2026, 7, 7+i*7, 13, 0, 0, 0, location),
			1,
			i,
			location,
		)
	}

	now := time.Date(2026, 7, 27, 20, 0, 0, 0, location) // Monday evening.
	comedyScore, confidence := profile.Score(comedy, now, location)
	dramaScore, _ := profile.Score(drama, now, location)
	if comedyScore <= dramaScore {
		t.Fatalf("Monday-evening comedy score %.3f <= drama score %.3f", comedyScore, dramaScore)
	}
	if confidence != 1 {
		t.Fatalf("confidence = %.3f, want 1 after repeated matching sessions", confidence)
	}
}

func TestContextAffinityUsesNeighboringWindowsAsWeakFallback(t *testing.T) {
	location := time.UTC
	profile := NewContextAffinityProfile()
	item := Item{Genres: []string{"Documentary"}}
	profile.Add(
		item,
		time.Date(2026, 7, 20, 16, 30, 0, 0, location), // Monday afternoon.
		0.8,
		0,
		location,
	)

	exact, exactConfidence := profile.Score(
		item, time.Date(2026, 7, 27, 16, 0, 0, 0, location), location,
	)
	neighbor, neighborConfidence := profile.Score(
		item, time.Date(2026, 7, 27, 18, 0, 0, 0, location), location,
	)
	if neighbor <= 0 || neighbor*neighborConfidence >= exact*exactConfidence {
		t.Fatalf(
			"weighted neighbor %.3f should be positive and below exact %.3f",
			neighbor*neighborConfidence,
			exact*exactConfidence,
		)
	}
	if neighborConfidence >= exactConfidence {
		t.Fatalf(
			"neighbor confidence %.3f should be below exact %.3f",
			neighborConfidence,
			exactConfidence,
		)
	}
}

func TestContextAffinityHasNeutralSparseHistoryFallback(t *testing.T) {
	score, confidence := (ContextAffinityProfile{}).Score(
		Item{Genres: []string{"Drama"}}, time.Now(), time.UTC,
	)
	if score != 0 || confidence != 0 {
		t.Fatalf("empty profile = score %.3f confidence %.3f, want neutral", score, confidence)
	}
}
