package registry

import (
	"fmt"
	"strings"
	"sync"
	"testing"

	"gitea.maximumdirect.net/eric/notarius/internal/core/source"
	"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
	scenecodec "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/scenedescriptions"
)

func TestResolveClassifiesExactMissingAndMismatchedChunks(t *testing.T) {
	registry := resolveList(t, sceneList(
		scene("chunk-combat", "session-alpha", 1, 2, dnd.SceneKindCombat, "Combat title", "Combat summary"),
	))

	for _, test := range []struct {
		name  string
		chunk *source.Chunk
		want  ChunkMatch
	}{
		{"exact", chunk("chunk-combat", "session-alpha", 1, 2), ChunkMatch{State: MatchExact, Kind: dnd.SceneKindCombat}},
		{"missing ID", chunk("chunk-missing", "session-alpha", 1, 2), ChunkMatch{State: MatchMissing}},
		{"source differs", chunk("chunk-combat", "other-source", 1, 2), ChunkMatch{State: MatchMismatched}},
		{"start differs", chunk("chunk-combat", "session-alpha", 2, 2), ChunkMatch{State: MatchMismatched}},
		{"end differs", chunk("chunk-combat", "session-alpha", 1, 3), ChunkMatch{State: MatchMismatched}},
	} {
		t.Run(test.name, func(t *testing.T) {
			if got := registry.Match(test.chunk); got != test.want {
				t.Fatalf("Match() = %#v, want %#v", got, test.want)
			}
		})
	}
}

func TestResolveRejectsInvalidSceneReferences(t *testing.T) {
	valid := encodeList(t, sceneList(scene("chunk-1", "session-alpha", 1, 2, dnd.SceneKindNarrative, "Arrival", "The party arrives.")))
	oversized := make([]byte, MaxBytes+1)
	for _, test := range []struct {
		name string
		set  contracts.ReferenceSet
	}{
		{"multiple items", referenceSet(referenceItem(valid), referenceItem(valid))},
		{"invalid media type", referenceSet(contracts.ReferenceItem{SlotName: ReferenceSlot, MediaType: "text/plain", Content: valid})},
		{"invalid media type syntax", referenceSet(contracts.ReferenceItem{SlotName: ReferenceSlot, MediaType: "not a media type", Content: valid})},
		{"oversized", referenceSet(contracts.ReferenceItem{SlotName: ReferenceSlot, MediaType: scenecodec.MediaType, Content: oversized})},
		{"invalid approved JSON", referenceSet(contracts.ReferenceItem{SlotName: ReferenceSlot, MediaType: scenecodec.MediaType, Content: []byte(`{"scenes":[]}`)})},
		{"duplicate IDs", referenceSet(referenceItem(encodeList(t, sceneList(
			scene("chunk-1", "session-alpha", 1, 1, dnd.SceneKindNarrative, "First", "First scene."),
			scene("chunk-1", "session-alpha", 2, 2, dnd.SceneKindCombat, "Second", "Second scene."),
		))))},
	} {
		t.Run(test.name, func(t *testing.T) {
			if _, err := Resolve(test.set); err == nil {
				t.Fatal("Resolve() error = nil")
			}
		})
	}
}

func TestResolveRejectsReversedEvidenceInDirectSceneReference(t *testing.T) {
	value := sceneList(scene("chunk-1", "session-alpha", 2, 1, dnd.SceneKindNarrative, "Arrival", "The party arrives."))
	content, err := scenecodec.New().EncodeCandidate(value)
	if err != nil {
		t.Fatalf("EncodeCandidate() error = %v", err)
	}
	if _, err := Resolve(referenceSet(referenceItem(content))); err == nil || !strings.Contains(err.Error(), "invalid approved") {
		t.Fatalf("Resolve() error = %v, want direct-reference rejection", err)
	}
}

func TestEligibilityDigestTracksOnlyGatingFields(t *testing.T) {
	base := sceneList(
		scene("chunk-a", "session-alpha", 1, 2, dnd.SceneKindNarrative, "Arrival", "The party arrives."),
		scene("chunk-b", "session-alpha", 3, 4, dnd.SceneKindCombat, "Combat", "Combat begins."),
	)
	baseDigest := resolveList(t, base).EligibilityDigest()

	equivalent := sceneList(
		scene("chunk-b", "session-alpha", 3, 4, dnd.SceneKindCombat, "Different title", "Different summary."),
		scene("chunk-a", "session-alpha", 1, 2, dnd.SceneKindNarrative, "Another title", "Another summary."),
	)
	if got := resolveList(t, equivalent).EligibilityDigest(); got != baseDigest {
		t.Fatalf("equivalent eligibility digest = %q, want %q", got, baseDigest)
	}

	changes := []struct {
		name   string
		change func(*dnd.SceneDescription)
	}{
		{"ID", func(value *dnd.SceneDescription) { value.ID = "chunk-other" }},
		{"source ID", func(value *dnd.SceneDescription) { value.SourceRef.SourceID = "session-other" }},
		{"start unit ID", func(value *dnd.SceneDescription) { value.SourceRef.StartUnitID = 2 }},
		{"end unit ID", func(value *dnd.SceneDescription) { value.SourceRef.EndUnitID = 3 }},
		{"kind", func(value *dnd.SceneDescription) { value.Kind = dnd.SceneKindRecap }},
	}
	for _, test := range changes {
		t.Run(test.name, func(t *testing.T) {
			changed := cloneList(base)
			test.change(&changed.Scenes[0])
			if got := resolveList(t, changed).EligibilityDigest(); got == baseDigest {
				t.Fatal("eligibility digest did not change")
			}
		})
	}
}

func TestResolverUsesGeneratedReferenceWhenPresent(t *testing.T) {
	external := sceneList(scene("chunk-1", "session-alpha", 1, 2, dnd.SceneKindNarrative, "External", "External scene."))
	generated := sceneList(scene("chunk-1", "session-alpha", 1, 2, dnd.SceneKindCombat, "Generated", "Generated scene."))
	resolver, err := NewResolver(referenceSet(referenceItem(encodeList(t, external))))
	if err != nil {
		t.Fatal(err)
	}
	if seeded := resolver.Seeded(); !seeded.Bound() || seeded.Count() != 1 || seeded.Match(chunk("chunk-1", "session-alpha", 1, 2)).Kind != dnd.SceneKindNarrative {
		t.Fatalf("Seeded() = %#v", seeded)
	}
	if got, err := resolver.Resolve(contracts.ReferenceSet{}); err != nil || got != resolver.Seeded() {
		t.Fatalf("Resolve() = %p, %v; want seeded %p", got, err, resolver.Seeded())
	}
	resolved, err := resolver.Resolve(referenceSet(referenceItem(encodeList(t, generated))))
	if err != nil {
		t.Fatal(err)
	}
	if got := resolved.Match(chunk("chunk-1", "session-alpha", 1, 2)); got != (ChunkMatch{State: MatchExact, Kind: dnd.SceneKindCombat}) {
		t.Fatalf("generated Match() = %#v", got)
	}
	if resolved == resolver.Seeded() {
		t.Fatal("generated reference reused a different seeded eligibility view")
	}

	unbound, err := NewResolver(contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ReferenceSlot: {}}})
	if err != nil {
		t.Fatal(err)
	}
	if seeded := unbound.Seeded(); seeded.Bound() || seeded.Count() != 0 || seeded.EligibilityDigest() != semanticDigest([]byte(emptyProjection)) {
		t.Fatalf("unbound Seeded() = %#v", seeded)
	}
}

func TestResolverReusesRawAndSemanticallyEquivalentViews(t *testing.T) {
	baseContent := encodeList(t, sceneList(
		scene("chunk-1", "session-alpha", 1, 2, dnd.SceneKindCombat, "Original title", "Original summary."),
	))
	baseItem := referenceItem(baseContent)
	baseItem.Digest = semanticDigest(baseContent)
	resolver, err := NewResolver(contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ReferenceSlot: {}}})
	if err != nil {
		t.Fatal(err)
	}

	first, err := resolver.Resolve(referenceSet(baseItem))
	if err != nil {
		t.Fatal(err)
	}
	second, err := resolver.Resolve(referenceSet(baseItem))
	if err != nil {
		t.Fatal(err)
	}
	if second != first {
		t.Fatal("identical framework reference did not reuse its immutable view")
	}

	equivalentContent := encodeList(t, sceneList(
		scene("chunk-1", "session-alpha", 1, 2, dnd.SceneKindCombat, "Revised title", "Revised summary."),
	))
	equivalentItem := referenceItem(equivalentContent)
	equivalentItem.Digest = semanticDigest(equivalentContent)
	equivalent, err := resolver.Resolve(referenceSet(equivalentItem))
	if err != nil {
		t.Fatal(err)
	}
	if equivalent != first {
		t.Fatal("prose-only change did not reuse the semantic eligibility view")
	}

	for _, digest := range []string{"", "not-a-sha256-digest"} {
		fallbackItem := referenceItem(baseContent)
		fallbackItem.Digest = digest
		fallback, resolveErr := resolver.Resolve(referenceSet(fallbackItem))
		if resolveErr != nil {
			t.Fatal(resolveErr)
		}
		if fallback != first {
			t.Fatalf("digest fallback %q did not reuse the content-addressed view", digest)
		}
	}
}

func TestRegistryIsImmutableAndResolverIsSafeForConcurrentReuse(t *testing.T) {
	content := encodeList(t, sceneList(scene("chunk-1", "session-alpha", 1, 2, dnd.SceneKindCombat, "Title", "Summary.")))
	references := referenceSet(referenceItem(content))
	registry := resolveReferences(t, references)
	content[0] = '['
	if got := registry.Match(chunk("chunk-1", "session-alpha", 1, 2)); got != (ChunkMatch{State: MatchExact, Kind: dnd.SceneKindCombat}) {
		t.Fatalf("Match() after input mutation = %#v", got)
	}

	resolver, err := NewResolver(contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ReferenceSlot: {}}})
	if err != nil {
		t.Fatal(err)
	}
	const workers = 32
	var group sync.WaitGroup
	errs := make(chan error, workers)
	for range workers {
		group.Add(1)
		go func() {
			defer group.Done()
			resolved, err := resolver.Resolve(references)
			if err != nil {
				errs <- err
				return
			}
			if got := resolved.Match(chunk("chunk-1", "session-alpha", 1, 2)); got != (ChunkMatch{State: MatchExact, Kind: dnd.SceneKindCombat}) {
				errs <- fmt.Errorf("Match() = %#v", got)
			}
		}()
	}
	group.Wait()
	close(errs)
	for err := range errs {
		t.Error(err)
	}
}

func resolveList(t *testing.T, value dnd.SceneDescriptionList) *Registry {
	t.Helper()
	return resolveReferences(t, referenceSet(referenceItem(encodeList(t, value))))
}

func resolveReferences(t *testing.T, references contracts.ReferenceSet) *Registry {
	t.Helper()
	registry, err := Resolve(references)
	if err != nil {
		t.Fatalf("Resolve() error = %v", err)
	}
	return registry
}

func encodeList(t *testing.T, value dnd.SceneDescriptionList) []byte {
	t.Helper()
	content, err := scenecodec.New().Encode(value)
	if err != nil {
		t.Fatalf("Encode() error = %v", err)
	}
	return content
}

func referenceSet(items ...contracts.ReferenceItem) contracts.ReferenceSet {
	return contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{ReferenceSlot: {Items: items}}}
}

func referenceItem(content []byte) contracts.ReferenceItem {
	return contracts.ReferenceItem{SlotName: ReferenceSlot, MediaType: scenecodec.MediaType, Content: append([]byte(nil), content...)}
}

func scene(id string, sourceID string, startUnitID int, endUnitID int, kind dnd.SceneKind, title string, summary string) dnd.SceneDescription {
	return dnd.SceneDescription{
		ID:        id,
		SourceRef: source.SourceRef{SourceID: sourceID, StartUnitID: startUnitID, EndUnitID: endUnitID},
		Kind:      kind,
		Title:     title,
		Summary:   summary,
	}
}

func sceneList(scenes ...dnd.SceneDescription) dnd.SceneDescriptionList {
	return dnd.SceneDescriptionList{Scenes: scenes}
}

func chunk(id string, sourceID string, startUnitID int, endUnitID int) *source.Chunk {
	return &source.Chunk{ID: id, Ref: source.SourceRef{SourceID: sourceID, StartUnitID: startUnitID, EndUnitID: endUnitID}}
}

func cloneList(value dnd.SceneDescriptionList) dnd.SceneDescriptionList {
	cloned := dnd.SceneDescriptionList{Scenes: append([]dnd.SceneDescription(nil), value.Scenes...)}
	return cloned
}
