package registry

import (
	"bytes"
	"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"
	locationcodec "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/locationregistry"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/locations/identity"
)

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

func TestResolveProjectsOrderedLocationsWithoutEvidence(t *testing.T) {
	registry := resolveList(t, registryFixture())
	if !registry.Bound() || registry.Count() != 2 || registry.Digest() == "" {
		t.Fatalf("registry identity = bound %t count %d digest %q", registry.Bound(), registry.Count(), registry.Digest())
	}
	projection := string(registry.PromptInput().Content)
	if !strings.Contains(projection, `"locations":[{"id":`) || !strings.Contains(projection, `"name":"The Tavern"`) || !strings.Contains(projection, `"name":"The Tavern"},{"id":`) {
		t.Fatalf("projection ordering = %s", projection)
	}
	for _, forbidden := range []string{"source_refs", "source_id", "session-alpha"} {
		if strings.Contains(projection, forbidden) {
			t.Fatalf("projection leaked %q: %s", forbidden, projection)
		}
	}
	if registry.PromptInput().Digest != registry.ProjectionDigest() || registry.Digest() == registry.ProjectionDigest() {
		t.Fatalf("full/projection digests = %q/%q", registry.Digest(), registry.ProjectionDigest())
	}
}

func TestRegistryLookupUsesIDAndReturnsDefensiveCopies(t *testing.T) {
	registry := resolveList(t, registryFixture())
	first := registry.Locations()[0]
	if got, ok := registry.Lookup(first.ID); !ok || got.Name != first.Name || !registry.Matches(first.ID, first.Name) || registry.Matches(first.ID, "Other Tavern") {
		t.Fatalf("ID lookup/match = %#v, %t", got, ok)
	}
	if _, ok := registry.Lookup("The Tavern"); ok {
		t.Fatal("Lookup accepted a name as an ID")
	}

	locations := registry.Locations()
	locations[0].Name = "changed"
	locations[0].SourceRefs[0].SourceID = "changed"
	canonical := registry.CanonicalBytes()
	canonical[0] = '['
	input := registry.PromptInput()
	input.Content[0] = '['
	if next, ok := registry.Lookup(first.ID); !ok || next.Name != first.Name || next.SourceRefs[0].SourceID != "session-alpha" {
		t.Fatalf("registry mutated through accessor: %#v, %t", next, ok)
	}
	if registry.CanonicalBytes()[0] != '{' || registry.PromptInput().Content[0] != '{' {
		t.Fatal("registry bytes mutated through accessor")
	}
}

func TestResolveRejectsInvalidReferenceInputs(t *testing.T) {
	valid := registryFixture()
	content, err := locationcodec.New().Encode(valid)
	if err != nil {
		t.Fatal(err)
	}
	invalidIdentity := append([]byte(nil), content...)
	invalidIdentity = bytes.Replace(invalidIdentity, []byte(valid.Locations[0].ID), []byte("location:sha256:0000000000000000000000000000000000000000000000000000000000000000"), 1)
	for _, test := range []struct {
		name string
		set  contracts.ReferenceSet
		want string
	}{
		{"empty bound slot", referenceSet(), "exactly one item"},
		{"multiple items", referenceSet(item(content), item(content)), "exactly one item"},
		{"malformed JSON", referenceSet(item([]byte(`{"locations":[`))), "invalid approved"},
		{"wrong media type", referenceSet(contracts.ReferenceItem{MediaType: "text/plain", Content: content}), "media type must be"},
		{"oversized", referenceSet(item(make([]byte, MaxBytes+1))), "limit"},
		{"invalid identity", referenceSet(item(invalidIdentity)), "id_mismatch"},
	} {
		t.Run(test.name, func(t *testing.T) {
			if _, err := Resolve(test.set); err == nil || !strings.Contains(err.Error(), test.want) {
				t.Fatalf("Resolve() error = %v, want %q", err, test.want)
			}
		})
	}
}

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)
	}

	validContent := encodeList(t, registryFixture())
	malformed := referenceSet(item([]byte(`{"locations":[`)))
	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(item(staticContent))
	seeded, err := NewResolver(staticReferences)
	if err != nil {
		t.Fatal(err)
	}
	resolved, err := seeded.Resolve(staticReferences)
	if err != nil || resolved != seeded.Seeded() {
		t.Fatalf("seed reuse = %p / %p, %v", resolved, seeded.Seeded(), 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 TestResolverReusesEquivalentCanonicalRegistries(t *testing.T) {
	resolver, err := NewResolver(referenceSet())
	if err != nil {
		t.Fatal(err)
	}
	content, err := locationcodec.New().Encode(registryFixture())
	if err != nil {
		t.Fatal(err)
	}
	firstSet := referenceSet(item(content))
	first, err := resolver.Resolve(firstSet)
	if err != nil {
		t.Fatal(err)
	}
	spaced := append([]byte("\n  "), content...)
	spaced = append(spaced, '\n')
	second, err := resolver.Resolve(referenceSet(contracts.ReferenceItem{MediaType: "APPLICATION/JSON; charset=utf-8", Content: spaced}))
	if err != nil || second != first {
		t.Fatalf("equivalent canonical registry = %p / %p, %v", first, second, err)
	}
}

func registryFixture() dnd.LocationRegistry {
	firstRefs := []source.SourceRef{{SourceID: "session-alpha", StartUnitID: 1, EndUnitID: 1}}
	secondRefs := []source.SourceRef{{SourceID: "session-alpha", StartUnitID: 2, EndUnitID: 2}}
	return dnd.LocationRegistry{Locations: []dnd.Location{
		{ID: identity.DeriveID("The Tavern", firstRefs), Name: "The Tavern", SourceRefs: firstRefs},
		{ID: identity.DeriveID("The Tavern", secondRefs), Name: "The Tavern", SourceRefs: secondRefs},
	}}
}

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

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

func item(content []byte) contracts.ReferenceItem {
	return contracts.ReferenceItem{SlotName: ReferenceSlot, MediaType: locationcodec.MediaType, Content: content}
}

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