package registry

import (
	"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"
	itemcodec "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/itemregistry"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/items/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 {
		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 TestResolveProjectsOrderedNamesWithoutEvidence(t *testing.T) {
	registry := resolveRegistry(t, fixture())
	if !registry.Bound() || registry.Digest() == "" || registry.Count() != 2 {
		t.Fatalf("registry identity = bound %t digest %q count %d", registry.Bound(), registry.Digest(), registry.Count())
	}
	want := `{"items":[{"name":"Silver Key"},{"name":"Healer's Kit"}]}`
	if got := string(registry.PromptInput().Content); got != want {
		t.Fatalf("prompt projection = %s, want %s", got, want)
	}
	for _, forbidden := range []string{"item: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 TestRegistryAccessorsAndLookupsAreDefensive(t *testing.T) {
	registry := resolveRegistry(t, fixture())
	if item, ok := registry.Lookup("  SILVER\u2003key "); !ok || item.Name != "Silver Key" {
		t.Fatalf("Lookup() = %#v, %t", item, ok)
	}
	if item, ok := registry.LookupID(identity.DeriveID("Healer's Kit")); !ok || item.Name != "Healer's Kit" {
		t.Fatalf("LookupID() = %#v, %t", item, ok)
	}
	if _, ok := registry.Lookup("Unknown Item"); ok {
		t.Fatal("Lookup() accepted an unknown item")
	}

	items := registry.Items()
	items[0].Name = "changed"
	items[0].SourceRefs[0].SourceID = "changed"
	list := registry.List()
	list.Items[1].Name = "changed"
	content := registry.CanonicalBytes()
	content[0] = '['
	input := registry.PromptInput()
	input.Content[0] = '['
	if next := registry.Items()[0]; next.Name != "Silver Key" || next.SourceRefs[0].SourceID != "session-alpha" {
		t.Fatalf("registry mutated through accessor: %#v", next)
	}
	if registry.List().Items[1].Name != "Healer's Kit" || registry.CanonicalBytes()[0] != '{' || registry.PromptInput().Content[0] != '{' {
		t.Fatal("registry bytes or records mutated through accessor")
	}
}

func TestResolveRejectsInvalidIdentityAndMalformedInput(t *testing.T) {
	duplicate := fixture()
	duplicate.Items = append(duplicate.Items, duplicate.Items[0])
	for _, references := range []contracts.ReferenceSet{
		referenceSet(contracts.ReferenceItem{MediaType: itemcodec.MediaType, Content: []byte(`{"items":[`)}),
		referenceSet(contracts.ReferenceItem{MediaType: "text/plain", Content: []byte(`{"items":[]}`)}),
		listReferenceSet(t, duplicate),
	} {
		if _, err := Resolve(references); err == nil {
			t.Fatalf("Resolve(%#v) error = nil", references)
		}
	}
}

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

func TestResolverKeepsConstructionAndOperationReferencesIndependent(t *testing.T) {
	resolver, err := NewResolver(contracts.ReferenceSet{})
	if err != nil || resolver.Seeded().Bound() {
		t.Fatalf("NewResolver() = %#v, %v", resolver, err)
	}

	valid := listReferenceSet(t, fixture())
	resolved, err := resolver.Resolve(valid)
	if err != nil || resolved.Count() != 2 {
		t.Fatalf("Resolve() = %#v, %v", resolved, err)
	}
	content := valid.Slots[ReferenceSlot].Items[0].Content
	content[0] = '['
	if resolved.CanonicalBytes()[0] != '{' {
		t.Fatal("registry retained mutable operation reference content")
	}
}

func fixture() dnd.ItemRegistry {
	return dnd.ItemRegistry{Items: []dnd.Item{
		{ID: identity.DeriveID("Silver Key"), Name: "Silver Key", SourceRefs: []source.SourceRef{{SourceID: "session-alpha", StartUnitID: 1, EndUnitID: 2}}},
		{ID: identity.DeriveID("Healer's Kit"), Name: "Healer's Kit", SourceRefs: []source.SourceRef{{SourceID: "session-alpha", StartUnitID: 3, EndUnitID: 3}}},
	}}
}

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

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

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