package registry

import (
	"bytes"
	"reflect"
	"strings"
	"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"
	npccodec "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/npcregistry"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/npcs/identity"
)

func TestResolveUnboundRegistryHasExactEmptyProjection(t *testing.T) {
	registry, err := Resolve(contracts.ReferenceSet{})
	if err != nil {
		t.Fatalf("Resolve() error = %v", err)
	}
	input := registry.PromptInput()
	if registry.Bound() || registry.Digest() != "" || registry.Count() != 0 || string(input.Content) != emptyPrompt || registry.IdentityDigest() != registry.ProjectionDigest() {
		t.Fatalf("registry = %#v input = %#v, want unbound empty registry", registry, input)
	}
	if registry.ProjectionDigest() == "" || input.Digest != registry.ProjectionDigest() || input.OriginURI != "" {
		t.Fatalf("projection digest/input = %q/%#v", registry.ProjectionDigest(), input)
	}
}

func TestResolveKeepsDurableProvenanceAndProjectsOnlyOrderedNames(t *testing.T) {
	list := registryFixture()
	registry := resolveList(t, list)
	if !registry.Bound() || registry.Digest() == "" || registry.Count() != 2 {
		t.Fatalf("registry identity = bound %t digest %q count %d", registry.Bound(), registry.Digest(), registry.Count())
	}
	if got := string(registry.PromptInput().Content); got != `{"npcs":[{"name":"Mira Thorn"},{"name":"Captain Vale"}]}` {
		t.Fatalf("prompt projection = %s", got)
	}
	for _, forbidden := range []string{"npc:sha256:", "source_refs", "source_id", "session-alpha"} {
		if strings.Contains(string(registry.PromptInput().Content), forbidden) {
			t.Fatalf("projection leaked %q: %s", forbidden, registry.PromptInput().Content)
		}
	}
	if registry.PromptInput().Digest != registry.ProjectionDigest() || registry.Digest() == registry.ProjectionDigest() {
		t.Fatalf("full/projection digests = %q/%q", registry.Digest(), registry.ProjectionDigest())
	}
}

func TestIdentityDigestTracksOrderedIDsAndNames(t *testing.T) {
	registry := resolveList(t, registryFixture())
	projection, err := identityProjection(registryFixture())
	if err != nil {
		t.Fatal(err)
	}
	want := `{"npcs":[{"id":"` + identity.DeriveID("Mira Thorn") + `","name":"Mira Thorn"},{"id":"` + identity.DeriveID("Captain Vale") + `","name":"Captain Vale"}]}`
	if string(projection) != want || registry.IdentityDigest() != semanticDigest(projection) || registry.IdentityDigest() == registry.ProjectionDigest() {
		t.Fatalf("identity digest = %q, want digest for %s", registry.IdentityDigest(), want)
	}
	if npc, ok := registry.LookupID(identity.DeriveID("Mira Thorn")); !ok || npc.Name != "Mira Thorn" {
		t.Fatalf("LookupID() = %#v, %t", npc, ok)
	}
	if _, ok := registry.LookupID("npc:unknown"); ok {
		t.Fatal("LookupID() accepted an unknown ID")
	}
}

func TestNameProjectionDigestTracksOnlyNamesAndOrder(t *testing.T) {
	base := registryFixture()
	evidenceChanged := registryFixture()
	evidenceChanged.NPCs[0].ID = "different application id"
	evidenceChanged.NPCs[0].SourceRefs = []source.SourceRef{{SourceID: "other", StartUnitID: 40, EndUnitID: 41}}
	baseBytes, err := nameProjection(base)
	if err != nil {
		t.Fatal(err)
	}
	changedBytes, err := nameProjection(evidenceChanged)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(baseBytes, changedBytes) || semanticDigest(baseBytes) != semanticDigest(changedBytes) {
		t.Fatalf("equivalent name projections differ: %s / %s", baseBytes, changedBytes)
	}

	nameChanged := registryFixture()
	nameChanged.NPCs[0].Name = "The Greencloak"
	nameBytes, _ := nameProjection(nameChanged)
	orderChanged := registryFixture()
	orderChanged.NPCs[0], orderChanged.NPCs[1] = orderChanged.NPCs[1], orderChanged.NPCs[0]
	orderBytes, _ := nameProjection(orderChanged)
	if bytes.Equal(baseBytes, nameBytes) || bytes.Equal(baseBytes, orderBytes) {
		t.Fatalf("name/order changes did not change projection: %s %s %s", baseBytes, nameBytes, orderBytes)
	}
}

func TestRegistryLookupAndAccessorsAreImmutable(t *testing.T) {
	registry := resolveList(t, registryFixture())
	if npc, ok := registry.Lookup("  mIRA\u2003thorn "); !ok || npc.Name != "Mira Thorn" {
		t.Fatalf("Lookup() = %#v, %t", npc, ok)
	}
	if _, ok := registry.Lookup("The Greencloak"); ok {
		t.Fatal("Lookup() accepted a non-canonical name")
	}

	npcs := registry.NPCs()
	npcs[0].Name = "changed"
	npcs[0].SourceRefs[0].SourceID = "changed"
	content := registry.CanonicalBytes()
	content[0] = '['
	input := registry.PromptInput()
	input.Content[0] = '['
	if next := registry.NPCs()[0]; next.Name != "Mira Thorn" || next.SourceRefs[0].SourceID != "session-alpha" {
		t.Fatalf("registry mutated through accessor: %#v", next)
	}
	if registry.CanonicalBytes()[0] != '{' || registry.PromptInput().Content[0] != '{' {
		t.Fatal("registry bytes mutated through accessor")
	}
}

func TestResolveRejectsMalformedOrUnsupportedRegistryInput(t *testing.T) {
	for _, item := range []contracts.ReferenceItem{
		{MediaType: "application/json", Content: []byte(`{"npcs":[`)},
		{MediaType: "text/plain", Content: []byte(`{"npcs":[]}`)},
	} {
		_, err := Resolve(referenceSet(item))
		if err == nil {
			t.Fatalf("Resolve(%s) error = nil", item.Content)
		}
	}
}

func TestResolveRejectsReversedEvidenceInDirectRegistryReference(t *testing.T) {
	value := registryFixture()
	value.NPCs[0].SourceRefs[0] = source.SourceRef{SourceID: "session-alpha", StartUnitID: 2, EndUnitID: 1}
	content, err := npccodec.New().EncodeCandidate(value)
	if err != nil {
		t.Fatalf("EncodeCandidate() error = %v", err)
	}
	if _, err := Resolve(referenceSet(contracts.ReferenceItem{MediaType: npccodec.MediaType, Content: content})); err == nil || !strings.Contains(err.Error(), "invalid approved") {
		t.Fatalf("Resolve() error = %v, want direct-reference rejection", err)
	}
}

func TestResolverReusesEquivalentCanonicalRegistries(t *testing.T) {
	set := listReferenceSet(t, registryFixture())
	resolver, err := NewResolver(contracts.ReferenceSet{})
	if err != nil {
		t.Fatal(err)
	}
	first, err := resolver.Resolve(set)
	if err != nil {
		t.Fatal(err)
	}
	content := set.Slots[ReferenceSlot].Items[0].Content
	equivalent := append([]byte("\n "), content...)
	equivalent = append(equivalent, '\n')
	second, err := resolver.Resolve(referenceSet(contracts.ReferenceItem{
		MediaType: "APPLICATION/JSON; charset=utf-8",
		Content:   equivalent,
	}))
	if err != nil || second != first {
		t.Fatalf("equivalent canonical registry = %p / %p, %v", first, second, err)
	}
}

func TestResolverHandlesConstructionAndOperationReferences(t *testing.T) {
	placeholder, err := NewResolver(referenceSet())
	if err != nil || placeholder.Seeded().Bound() {
		t.Fatalf("generated placeholder = %#v, %v; want unbound seed", placeholder, err)
	}

	valid := listReferenceSet(t, registryFixture())
	validContent := valid.Slots[ReferenceSlot].Items[0].Content
	malformed := referenceSet(contracts.ReferenceItem{MediaType: npccodec.MediaType, Content: []byte(`{"npcs":[`)})
	if _, err := NewResolver(malformed); err == nil {
		t.Fatal("NewResolver(malformed) error = nil")
	}
	if _, err := placeholder.Resolve(malformed); err == nil {
		t.Fatal("Resolve(malformed) error = nil")
	}

	staticContent := append([]byte(nil), validContent...)
	staticReferences := referenceSet(contracts.ReferenceItem{MediaType: npccodec.MediaType, Content: staticContent})
	seeded, err := NewResolver(staticReferences)
	if err != nil {
		t.Fatal(err)
	}
	staticContent[0] = '['
	delete(staticReferences.Slots, ReferenceSlot)
	if seeded.Seeded().Count() != 2 || seeded.Seeded().CanonicalBytes()[0] != '{' {
		t.Fatalf("seeded registry retained construction references: %#v", seeded.Seeded())
	}
	if fallback, err := seeded.Resolve(contracts.ReferenceSet{}); err != nil || fallback != seeded.Seeded() {
		t.Fatalf("fallback = %#v, %v; want seeded registry", fallback, err)
	}
}

func registryFixture() dnd.NPCRegistry {
	return dnd.NPCRegistry{NPCs: []dnd.NPC{
		{ID: identity.DeriveID("Mira Thorn"), Name: "Mira Thorn", SourceRefs: []source.SourceRef{{SourceID: "session-alpha", StartUnitID: 1, EndUnitID: 2}}},
		{ID: identity.DeriveID("Captain Vale"), Name: "Captain Vale", SourceRefs: []source.SourceRef{{SourceID: "session-alpha", StartUnitID: 3, EndUnitID: 3}}},
	}}
}

func resolveList(t *testing.T, list dnd.NPCRegistry) *Registry {
	t.Helper()
	registry, err := Resolve(listReferenceSet(t, list))
	if err != nil {
		t.Fatalf("Resolve() error = %v", err)
	}
	return registry
}

func listReferenceSet(t *testing.T, list dnd.NPCRegistry) contracts.ReferenceSet {
	t.Helper()
	content, err := npccodec.New().Encode(list)
	if err != nil {
		t.Fatalf("Encode() error = %v", err)
	}
	return referenceSet(contracts.ReferenceItem{SlotName: ReferenceSlot, MediaType: npccodec.MediaType, Content: content})
}

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

func TestProjectionIsStableForEquivalentNormalizedRegistries(t *testing.T) {
	first := resolveList(t, registryFixture())
	secondList := registryFixture()
	secondList.NPCs[0].SourceRefs = append(secondList.NPCs[0].SourceRefs, source.SourceRef{SourceID: "session-beta", StartUnitID: 8, EndUnitID: 8})
	second := resolveList(t, secondList)
	if !reflect.DeepEqual(first.PromptInput().Content, second.PromptInput().Content) || first.ProjectionDigest() != second.ProjectionDigest() || first.IdentityDigest() != second.IdentityDigest() || first.Digest() == second.Digest() {
		t.Fatalf("projection/full identity mismatch: %#v %#v", first, second)
	}
}
