package identity

import (
	"reflect"
	"strings"
	"testing"

	"gitea.maximumdirect.net/eric/notarius/internal/core/source"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
)

func TestNormalizeDisplayOnlyChangesWhitespace(t *testing.T) {
	if got, want := NormalizeDisplay("  The\u2003Old\nTavern  "), "The Old Tavern"; got != want {
		t.Fatalf("NormalizeDisplay() = %q, want %q", got, want)
	}
}

func TestDeriveIDUsesDocumentedCompactJSONInput(t *testing.T) {
	refs := []source.SourceRef{
		{SourceID: "session-alpha", StartUnitID: 9, EndUnitID: 9},
		{SourceID: "session-alpha", StartUnitID: 3, EndUnitID: 9},
		{SourceID: "session-alpha", StartUnitID: 3, EndUnitID: 9},
	}
	const want = "location:sha256:c099f7780a3cfd8c4094441d3a3e906f4f1e79c27589f95dfad573f86f308845"

	if got := DeriveID("  The\u2003Tavern ", refs); got != want {
		t.Fatalf("DeriveID() = %q, want %q", got, want)
	}
	if got := IDFor("The Tavern", refs); got != want {
		t.Fatalf("IDFor() = %q, want %q", got, want)
	}
}

func TestDeriveIDUsesEarliestCanonicalEvidenceWithoutMutatingInput(t *testing.T) {
	refs := []source.SourceRef{
		{SourceID: "zeta", StartUnitID: 1, EndUnitID: 1},
		{SourceID: "alpha", StartUnitID: 8, EndUnitID: 8},
		{SourceID: "alpha", StartUnitID: 2, EndUnitID: 3},
	}
	wantRefs := append([]source.SourceRef(nil), refs...)

	first := DeriveID("The Tavern", refs)
	second := DeriveID("The Tavern", []source.SourceRef{refs[2], refs[0], refs[1]})
	if first != second {
		t.Fatalf("DeriveID() changed when evidence order changed: %q != %q", first, second)
	}
	if !reflect.DeepEqual(refs, wantRefs) {
		t.Fatalf("DeriveID() mutated refs: got %#v, want %#v", refs, wantRefs)
	}
}

func TestDeriveIDDistinguishesSameNameAtDifferentEvidenceAnchors(t *testing.T) {
	first := DeriveID("The Tavern", []source.SourceRef{{SourceID: "session", StartUnitID: 3, EndUnitID: 3}})
	second := DeriveID("the\u00a0tavern", []source.SourceRef{{SourceID: "session", StartUnitID: 18, EndUnitID: 18}})
	if first == "" || second == "" || first == second {
		t.Fatalf("same-name locations have IDs %q and %q, want distinct nonempty IDs", first, second)
	}
}

func TestDeriveIDRejectsMissingIdentityComponents(t *testing.T) {
	for _, tt := range []struct {
		name      string
		nameValue string
		refs      []source.SourceRef
	}{
		{name: "blank name", nameValue: " \u2003 ", refs: []source.SourceRef{{SourceID: "session", StartUnitID: 1, EndUnitID: 1}}},
		{name: "missing refs", nameValue: "The Tavern"},
		{name: "malformed ref", nameValue: "The Tavern", refs: []source.SourceRef{{SourceID: " ", StartUnitID: 1, EndUnitID: 1}}},
	} {
		t.Run(tt.name, func(t *testing.T) {
			if got := DeriveID(tt.nameValue, tt.refs); got != "" {
				t.Fatalf("DeriveID() = %q, want empty ID", got)
			}
		})
	}
}

func TestDeriveIDRejectsReversedOnlyEvidence(t *testing.T) {
	if got := DeriveID("The Tavern", []source.SourceRef{{SourceID: "session", StartUnitID: 2, EndUnitID: 1}}); got != "" {
		t.Fatalf("DeriveID() = %q, want empty ID", got)
	}
	valid := source.SourceRef{SourceID: "session", StartUnitID: 3, EndUnitID: 3}
	if got, want := DeriveID("The Tavern", []source.SourceRef{{SourceID: "session", StartUnitID: 2, EndUnitID: 1}, valid}), DeriveID("The Tavern", []source.SourceRef{valid}); got != want {
		t.Fatalf("DeriveID() = %q, want %q after filtering reversed evidence", got, want)
	}
}

func TestIsValidID(t *testing.T) {
	valid := DeriveID("The Tavern", []source.SourceRef{{SourceID: "session", StartUnitID: 1, EndUnitID: 1}})
	if !IsValidID(valid) || !ValidID(valid) {
		t.Fatalf("derived ID %q is not valid", valid)
	}
	for _, value := range []string{"", "location:sha256:", "location:sha256:" + strings.Repeat("A", 64), "location:sha256:" + strings.Repeat("0", 63)} {
		if IsValidID(value) {
			t.Fatalf("IsValidID(%q) = true, want false", value)
		}
	}
}

func TestValidateRegistryAllowsSameComparisonNameWithDifferentAnchors(t *testing.T) {
	firstRefs := []source.SourceRef{{SourceID: "session", StartUnitID: 2, EndUnitID: 2}}
	secondRefs := []source.SourceRef{{SourceID: "session", StartUnitID: 8, EndUnitID: 8}}
	locations := []dnd.Location{
		{ID: DeriveID("The Tavern", firstRefs), Name: "The Tavern", SourceRefs: firstRefs},
		{ID: DeriveID("the\u00a0tavern", secondRefs), Name: "the\u00a0tavern", SourceRefs: secondRefs},
	}
	if issues := ValidateRegistry(locations); len(issues) != 0 {
		t.Fatalf("ValidateRegistry() = %#v, want no issues", issues)
	}
}

func TestValidateRegistryReportsIdentityProblemsDeterministicallyWithoutMutation(t *testing.T) {
	refs := []source.SourceRef{{SourceID: "session", StartUnitID: 2, EndUnitID: 2}}
	validID := DeriveID("The Tavern", refs)
	locations := []dnd.Location{
		{ID: validID, Name: "The Tavern", SourceRefs: refs},
		{ID: validID, Name: "Elsewhere", SourceRefs: refs},
		{ID: "bad", Name: "", SourceRefs: nil},
	}
	wantLocations := cloneLocations(locations)

	issues := ValidateList(dnd.LocationRegistry{Locations: locations})
	want := []Issue{
		{Code: IssueIDMismatch, RecordIndex: 1, Value: validID},
		{Code: IssueEmptyCanonicalName, RecordIndex: 2, Value: ""},
		{Code: IssueMissingEvidence, RecordIndex: 2},
		{Code: IssueInvalidID, RecordIndex: 2, Value: "bad"},
		{Code: IssueDuplicateID, RecordIndex: 1, Value: validID},
	}
	if !reflect.DeepEqual(issues, want) {
		t.Fatalf("ValidateList() = %#v, want %#v", issues, want)
	}
	if !reflect.DeepEqual(locations, wantLocations) {
		t.Fatalf("ValidateList() mutated locations: got %#v, want %#v", locations, wantLocations)
	}
}

func cloneLocations(input []dnd.Location) []dnd.Location {
	output := make([]dnd.Location, len(input))
	copy(output, input)
	for index := range output {
		output[index].SourceRefs = append([]source.SourceRef(nil), input[index].SourceRefs...)
	}
	return output
}
