package enemyevents

import (
	"context"
	"encoding/json"
	"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/framework/pipeline"
	"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 TestNormalizeCanonicalizesSubjectsEvidenceOrderAndDuplicates(t *testing.T) {
	document := &source.SourceDocument{ID: "session", Units: []source.SourceUnit{{ID: 30}, {ID: 10}, {ID: 20}, {ID: 40}}}
	ref := func(unitID int) []source.SourceRef {
		return []source.SourceRef{{SourceID: document.ID, StartUnitID: unitID, EndUnitID: unitID}}
	}
	input := dnd.EnemyEventList{Events: []dnd.EnemyEvent{
		{Name: "  áRIA  ", Kind: dnd.EnemyEventKindKilled, SourceRefs: append(ref(30), ref(10)...)},
		{Name: "  Remaining   Orcs ", Kind: dnd.EnemyEventKindEngaged, SourceRefs: ref(20)},
		{Name: "Ária", Kind: dnd.EnemyEventKindKilled, SourceRefs: []source.SourceRef{{SourceID: document.ID, StartUnitID: 10, EndUnitID: 10}, {SourceID: document.ID, StartUnitID: 30, EndUnitID: 30}}},
		{Name: "Ária", Kind: dnd.EnemyEventKindFled, SourceRefs: ref(40)},
	}}
	originalRefs := append([]source.SourceRef(nil), input.Events[0].SourceRefs...)
	normalizer := newNormalizer(t, npcReferences(t))
	result, err := normalizer.Normalize(context.Background(), normalizeRequest(document, input, contracts.ReferenceSet{}))
	if err != nil {
		t.Fatal(err)
	}
	got := result.Value.Events
	if len(got) != 3 || got[0].Name != "Ária" || got[0].Kind != dnd.EnemyEventKindKilled || !reflect.DeepEqual(got[0].SourceRefs, []source.SourceRef{{SourceID: document.ID, StartUnitID: 30, EndUnitID: 30}, {SourceID: document.ID, StartUnitID: 10, EndUnitID: 10}}) || got[1].Name != "Remaining Orcs" || got[2].Kind != dnd.EnemyEventKindFled {
		t.Fatalf("normalized events = %#v", got)
	}
	for _, reason := range []string{ReasonCodeNameCanonicalized, ReasonCodeSourceRefsNormalized, ReasonCodeEventsReordered, ReasonCodeDuplicateCollapsed} {
		if !hasDiagnostic(result.Diagnostics, reason) {
			t.Fatalf("diagnostics = %#v, missing %q", result.Diagnostics, reason)
		}
	}
	if !reflect.DeepEqual(input.Events[0].SourceRefs, originalRefs) {
		t.Fatalf("Normalize() mutated input: %#v", input)
	}
	got[0].SourceRefs[0].StartUnitID = 999
	if input.Events[0].SourceRefs[0].StartUnitID == 999 {
		t.Fatal("normalized source references alias input")
	}
}

func TestNormalizeUsesExplicitKindOrderAndPreservesDistinctObservations(t *testing.T) {
	document := &source.SourceDocument{ID: "session", Units: []source.SourceUnit{{ID: 1}, {ID: 2}, {ID: 3}}}
	ref := func(unitID int) []source.SourceRef {
		return []source.SourceRef{{SourceID: document.ID, StartUnitID: unitID, EndUnitID: unitID}}
	}
	input := dnd.EnemyEventList{Events: []dnd.EnemyEvent{
		{Name: "Ashfang", Kind: dnd.EnemyEventKindKilled, SourceRefs: ref(1)},
		{Name: "Ashfang", Kind: dnd.EnemyEventKindFled, SourceRefs: ref(1)},
		{Name: "Ashfang", Kind: dnd.EnemyEventKindCaptured, SourceRefs: ref(1)},
		{Name: "Ashfang", Kind: dnd.EnemyEventKindIncapacitated, SourceRefs: ref(1)},
		{Name: "Ashfang", Kind: dnd.EnemyEventKindEngaged, SourceRefs: ref(1)},
		{Name: "Ashfang", Kind: dnd.EnemyEventKindEngaged, SourceRefs: ref(3)},
	}}
	result, err := newNormalizer(t, npcReferences(t)).Normalize(context.Background(), normalizeRequest(document, input, contracts.ReferenceSet{}))
	if err != nil {
		t.Fatal(err)
	}
	want := []dnd.EnemyEventKind{
		dnd.EnemyEventKindEngaged,
		dnd.EnemyEventKindIncapacitated,
		dnd.EnemyEventKindCaptured,
		dnd.EnemyEventKindFled,
		dnd.EnemyEventKindKilled,
		dnd.EnemyEventKindEngaged,
	}
	for index, kind := range want {
		if result.Value.Events[index].Kind != kind {
			t.Fatalf("event %d kind = %q, want %q", index, result.Value.Events[index].Kind, kind)
		}
	}
}

func TestNormalizePreservesDistinctEvidenceWhenEncodedKeysCoincide(t *testing.T) {
	invalidSourceID := string([]byte{'s', 0xff})
	replacementSourceID := "s\uFFFD"
	document := &source.SourceDocument{ID: invalidSourceID, Units: []source.SourceUnit{{ID: 1}}}
	input := dnd.EnemyEventList{Events: []dnd.EnemyEvent{
		{Name: "Ashfang", Kind: dnd.EnemyEventKindEngaged, SourceRefs: []source.SourceRef{{SourceID: invalidSourceID, StartUnitID: 1, EndUnitID: 1}}},
		{Name: "Ashfang", Kind: dnd.EnemyEventKindEngaged, SourceRefs: []source.SourceRef{{SourceID: replacementSourceID, StartUnitID: 1, EndUnitID: 1}}},
	}}

	result, err := newNormalizer(t, npcReferences(t)).Normalize(context.Background(), normalizeRequest(document, input, contracts.ReferenceSet{}))
	if err != nil || len(result.Value.Events) != 2 || hasDiagnostic(result.Diagnostics, ReasonCodeDuplicateCollapsed) {
		t.Fatalf("Normalize() = %#v, %v; want distinct evidence observations retained", result, err)
	}
}

func TestNormalizeIsIdempotentAndPreservesEmptyRepresentation(t *testing.T) {
	normalizer := newNormalizer(t, npcReferences(t))
	for _, input := range []dnd.EnemyEventList{{}, {Events: []dnd.EnemyEvent{}}} {
		result, err := normalizer.Normalize(context.Background(), normalizeRequest(testDocument(), input, contracts.ReferenceSet{}))
		if err != nil || (result.Value.Events == nil) != (input.Events == nil) {
			t.Fatalf("Normalize() = %#v, %v for %#v", result, err, input)
		}
	}
	input := dnd.EnemyEventList{Events: []dnd.EnemyEvent{{Name: "  Remaining orcs ", Kind: dnd.EnemyEventKindEngaged, SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 20, EndUnitID: 20}}}}}
	first, err := normalizer.Normalize(context.Background(), normalizeRequest(testDocument(), input, contracts.ReferenceSet{}))
	if err != nil {
		t.Fatal(err)
	}
	second, err := normalizer.Normalize(context.Background(), normalizeRequest(testDocument(), first.Value, contracts.ReferenceSet{}))
	if err != nil || !reflect.DeepEqual(second.Value, first.Value) || len(second.Diagnostics) != 0 {
		t.Fatalf("second normalization = %#v, %v", second, err)
	}
}

func TestNormalizeRequiresRegistryAndKeepsOperationContentOutOfMetadata(t *testing.T) {
	normalizer, err := New(Options{})
	if err != nil {
		t.Fatal(err)
	}
	if _, err := normalizer.Normalize(context.Background(), normalizeRequest(testDocument(), dnd.EnemyEventList{}, contracts.ReferenceSet{})); err == nil || !strings.Contains(err.Error(), "NPC registry") {
		t.Fatalf("Normalize() error = %v", err)
	}
	operationReferences := npcReferences(t)
	result, err := normalizer.Normalize(context.Background(), normalizeRequest(testDocument(), dnd.EnemyEventList{Events: []dnd.EnemyEvent{}}, operationReferences))
	if err != nil || result.Value.Events == nil {
		t.Fatalf("Normalize() = %#v, %v", result, err)
	}
	if metadata := normalizer.ManifestMetadata(); metadata["npc_registry_digest"] != nil {
		t.Fatalf("operation registry leaked into metadata: %#v", metadata)
	}
}

func TestNormalizerContractAndFindingBound(t *testing.T) {
	normalizer := newNormalizer(t, npcReferences(t))
	if _, err := DecodeOptions(map[string]any{"unexpected": true}); err == nil {
		t.Fatal("DecodeOptions() accepted an unknown option")
	}
	first := ModuleSpec()
	first.ReferenceSlots[0].AcceptedMediaTypes[0] = "changed"
	second := ModuleSpec()
	if second.Key != Key || second.Stage != pipeline.StageNormalize || second.ExecutionClass != contracts.ExecutionClassDeterministic || second.ArtifactKind != dnd.EnemyEventListKind || second.ReferenceSlots[0].AcceptedMediaTypes[0] != "application/json" {
		t.Fatalf("ModuleSpec() = %#v", second)
	}
	registry := pipeline.NewNormalizerRegistry()
	if err := Register(registry); err != nil {
		t.Fatal(err)
	}
	if spec, ok := registry.Spec(Key); !ok || spec.ArtifactKind != dnd.EnemyEventListKind {
		t.Fatalf("registered spec = %#v, %t", spec, ok)
	}
	metadata := normalizer.ManifestMetadata()
	if metadata["normalization_policy"] != normalizationPolicy || !strings.HasPrefix(metadata["npc_registry_digest"].(string), "sha256:") {
		t.Fatalf("metadata = %#v", metadata)
	}
	encoded, err := json.Marshal(metadata)
	if err != nil || strings.Contains(string(encoded), "Ária") {
		t.Fatalf("unsafe metadata = %s, %v", encoded, err)
	}

	count := contracts.MaxDiagnosticSamples + 5
	document := &source.SourceDocument{ID: "session", Units: make([]source.SourceUnit, count)}
	input := dnd.EnemyEventList{Events: make([]dnd.EnemyEvent, count)}
	for index := range document.Units {
		document.Units[index].ID = index + 1
		input.Events[index] = dnd.EnemyEvent{Name: "  ÁRIA ", Kind: dnd.EnemyEventKindEngaged, SourceRefs: []source.SourceRef{{SourceID: document.ID, StartUnitID: count - index, EndUnitID: count - index}}}
	}
	result, err := normalizer.Normalize(context.Background(), normalizeRequest(document, input, contracts.ReferenceSet{}))
	if err != nil || len(result.Diagnostics) == 0 {
		t.Fatalf("diagnostics = %#v, %v", result.Diagnostics, err)
	}
}

func newNormalizer(t *testing.T, references contracts.ReferenceSet) *Normalizer {
	t.Helper()
	normalizer, err := New(Options{}, references)
	if err != nil {
		t.Fatal(err)
	}
	return normalizer
}

func normalizeRequest(document *source.SourceDocument, value dnd.EnemyEventList, references contracts.ReferenceSet) contracts.TypedNormalizeRequest[dnd.EnemyEventList] {
	return contracts.TypedNormalizeRequest[dnd.EnemyEventList]{
		Source:      document,
		MergeOutput: contracts.MergeArtifact[dnd.EnemyEventList]{Value: value},
		References:  references,
	}
}

func testDocument() *source.SourceDocument {
	return &source.SourceDocument{ID: "session", Units: []source.SourceUnit{{ID: 10}, {ID: 20}, {ID: 30}}}
}

func npcReferences(t *testing.T) contracts.ReferenceSet {
	t.Helper()
	value := dnd.NPCRegistry{NPCs: []dnd.NPC{{
		ID: identity.DeriveID("Ária"), Name: "Ária",
		SourceRefs: []source.SourceRef{{SourceID: "registry", StartUnitID: 1, EndUnitID: 1}},
	}}}
	content, err := npccodec.New().Encode(value)
	if err != nil {
		t.Fatal(err)
	}
	return contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{NPCRegistryReferenceSlot: {
		Slot:  contracts.ReferenceSlot{Name: NPCRegistryReferenceSlot},
		Items: []contracts.ReferenceItem{{SlotName: NPCRegistryReferenceSlot, MediaType: npccodec.MediaType, Content: content}},
	}}}
}

func hasDiagnostic(diagnostics []contracts.ProducerDiagnostic, reason string) bool {
	for _, diagnostic := range diagnostics {
		if diagnostic.ReasonCode == reason && diagnostic.Disposition == contracts.DiagnosticDispositionObservation {
			return true
		}
	}
	return false
}
