package npcoccurrences

import (
	"context"
	"reflect"
	"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 TestNormalizeValidatesPairsAndClones(t *testing.T) {
	doc := &source.SourceDocument{ID: "session", Units: []source.SourceUnit{{ID: 30}, {ID: 10}}}
	normalizer, err := New(Options{}, npcReferences(t))
	if err != nil {
		t.Fatalf("New() error = %v", err)
	}
	input := dnd.NPCOccurrenceList{Occurrences: []dnd.NPCOccurrence{{
		NPCID: identity.DeriveID("Ária"), Name: "Ária", Kind: dnd.NPCOccurrenceKindDialogue,
		SourceRefs: []source.SourceRef{{SourceID: doc.ID, StartUnitID: 30, EndUnitID: 30}, {SourceID: doc.ID, StartUnitID: 10, EndUnitID: 10}, {SourceID: doc.ID, StartUnitID: 30, EndUnitID: 30}},
	}}}
	original := append([]source.SourceRef(nil), input.Occurrences[0].SourceRefs...)
	result, err := normalizer.Normalize(context.Background(), contracts.TypedNormalizeRequest[dnd.NPCOccurrenceList]{Source: doc, MergeOutput: contracts.MergeArtifact[dnd.NPCOccurrenceList]{Value: input}})
	if err != nil {
		t.Fatalf("Normalize() error = %v", err)
	}
	got := result.Value.Occurrences[0]
	if got.NPCID != identity.DeriveID("Ária") || got.Name != "Ária" || !reflect.DeepEqual(got.SourceRefs, []source.SourceRef{{SourceID: doc.ID, StartUnitID: 30, EndUnitID: 30}, {SourceID: doc.ID, StartUnitID: 10, EndUnitID: 10}}) {
		t.Fatalf("normalized occurrence = %#v", got)
	}
	if !hasDiagnostic(result.Diagnostics, ReasonCodeSourceRefsNormalized) {
		t.Fatalf("diagnostics = %#v", result.Diagnostics)
	}
	if !reflect.DeepEqual(input.Occurrences[0].SourceRefs, original) {
		t.Fatalf("Normalize() mutated input: %#v", input)
	}
	second, err := normalizer.Normalize(context.Background(), contracts.TypedNormalizeRequest[dnd.NPCOccurrenceList]{Source: doc, MergeOutput: contracts.MergeArtifact[dnd.NPCOccurrenceList]{Value: result.Value}})
	if err != nil || !reflect.DeepEqual(second.Value, result.Value) || len(second.Diagnostics) != 0 {
		t.Fatalf("second normalization = %#v, %v; want idempotent output without findings", second, err)
	}
	result.Value.Occurrences[0].SourceRefs[0].StartUnitID = 999
	if input.Occurrences[0].SourceRefs[0].StartUnitID == 999 {
		t.Fatal("normalized source refs share input storage")
	}
}

func TestNormalizeRequiresOperationRegistryAndPreservesEmptyRepresentation(t *testing.T) {
	normalizer, err := New(Options{})
	if err != nil {
		t.Fatalf("New() error = %v", err)
	}
	if _, err := normalizer.Normalize(context.Background(), contracts.TypedNormalizeRequest[dnd.NPCOccurrenceList]{}); err == nil {
		t.Fatal("Normalize() accepted an unbound NPC registry")
	}
	for _, input := range []dnd.NPCOccurrenceList{{}, {Occurrences: []dnd.NPCOccurrence{}}} {
		result, err := normalizer.Normalize(context.Background(), contracts.TypedNormalizeRequest[dnd.NPCOccurrenceList]{
			MergeOutput: contracts.MergeArtifact[dnd.NPCOccurrenceList]{Value: input}, References: npcReferences(t),
		})
		if err != nil || (result.Value.Occurrences == nil) != (input.Occurrences == nil) {
			t.Fatalf("Normalize() = %#v, %v for input %#v", result, err, input)
		}
	}
	if metadata := normalizer.ManifestMetadata(); metadata["npc_registry_digest"] != nil || metadata["npc_count"] != nil {
		t.Fatalf("operation registry leaked into metadata: %#v", metadata)
	}
}

func TestNormalizeRejectsUnknownIDsAndMismatchedNames(t *testing.T) {
	doc := testDocument()
	normalizer, err := New(Options{}, npcReferences(t))
	if err != nil {
		t.Fatal(err)
	}
	for _, occurrence := range []dnd.NPCOccurrence{
		occurrence("Unknown NPC", dnd.NPCOccurrenceKindOther, source.SourceRef{SourceID: doc.ID, StartUnitID: 10, EndUnitID: 10}),
		{NPCID: identity.DeriveID("Ária"), Name: "Borin", Kind: dnd.NPCOccurrenceKindOther, SourceRefs: []source.SourceRef{{SourceID: doc.ID, StartUnitID: 10, EndUnitID: 10}}},
	} {
		input := dnd.NPCOccurrenceList{Occurrences: []dnd.NPCOccurrence{occurrence}}
		if result, err := normalizer.Normalize(context.Background(), contracts.TypedNormalizeRequest[dnd.NPCOccurrenceList]{Source: doc, MergeOutput: contracts.MergeArtifact[dnd.NPCOccurrenceList]{Value: input}}); err == nil {
			t.Fatalf("Normalize() = %#v, %v; want registry pair rejection", result, err)
		}
	}
}

func TestNormalizeOrdersAndCollapsesExactDuplicatesOnly(t *testing.T) {
	doc := &source.SourceDocument{ID: "session", Units: []source.SourceUnit{{ID: 50}, {ID: 10}, {ID: 90}}}
	ref := func(unit int) source.SourceRef {
		return source.SourceRef{SourceID: doc.ID, StartUnitID: unit, EndUnitID: unit}
	}
	first := occurrence("Ária", dnd.NPCOccurrenceKindDialogue, ref(50))
	input := dnd.NPCOccurrenceList{Occurrences: []dnd.NPCOccurrence{
		occurrence("Borin", dnd.NPCOccurrenceKindMentioned, ref(90)),
		first,
		first,
		occurrence("Ária", dnd.NPCOccurrenceKindCombatAlly, ref(50)),
		occurrence("Ária", dnd.NPCOccurrenceKindDialogue, ref(10)),
		occurrence("Ária", dnd.NPCOccurrenceKindDialogue, ref(999)),
	}}
	normalizer, err := New(Options{}, npcReferences(t))
	if err != nil {
		t.Fatal(err)
	}
	result, err := normalizer.Normalize(context.Background(), contracts.TypedNormalizeRequest[dnd.NPCOccurrenceList]{Source: doc, MergeOutput: contracts.MergeArtifact[dnd.NPCOccurrenceList]{Value: input}})
	if err != nil {
		t.Fatal(err)
	}
	got := result.Value.Occurrences
	if len(got) != 5 {
		t.Fatalf("occurrence count = %d, want 5: %#v", len(got), got)
	}
	if got[0].Kind != dnd.NPCOccurrenceKindCombatAlly || got[0].SourceRefs[0].StartUnitID != 50 || got[1].SourceRefs[0].StartUnitID != 50 || got[2].SourceRefs[0].StartUnitID != 10 || got[3].SourceRefs[0].StartUnitID != 90 || got[4].SourceRefs[0].StartUnitID != 999 {
		t.Fatalf("canonical order = %#v", got)
	}
	if !hasDiagnostic(result.Diagnostics, ReasonCodeOccurrencesReordered) || !hasDiagnostic(result.Diagnostics, ReasonCodeDuplicateCollapsed) {
		t.Fatalf("diagnostics = %#v", result.Diagnostics)
	}
}

func TestNormalizerContractAndDeterministicFindings(t *testing.T) {
	normalizer, err := New(Options{}, npcReferences(t))
	if err != nil {
		t.Fatal(err)
	}
	if spec := ModuleSpec(); spec.Key != Key || spec.Stage != pipeline.StageNormalize || spec.ArtifactKind != dnd.NPCOccurrenceListKind || len(spec.ReferenceSlots) != 1 || spec.ReferenceSlots[0].Name != NPCRegistryReferenceSlot || !spec.ReferenceSlots[0].Required {
		t.Fatalf("ModuleSpec() = %#v", spec)
	}
	if metadata := normalizer.ManifestMetadata(); metadata["normalization_policy"] != normalizationPolicy || metadata["npc_registry_digest"] == "" || metadata["npc_count"] != 2 {
		t.Fatalf("metadata = %#v", metadata)
	}
	if fingerprints := normalizer.CheckpointFingerprints(); len(fingerprints) != 2 || fingerprints[1].Name != "npc_registry" || fingerprints[1].Value == "" {
		t.Fatalf("fingerprints = %#v", fingerprints)
	}
	if _, err := DecodeOptions(map[string]any{"unexpected": true}); err == nil {
		t.Fatal("DecodeOptions() accepted an unknown option")
	}
}

func TestNormalizeBoundsFindings(t *testing.T) {
	count := contracts.MaxDiagnosticSamples + 5
	doc := &source.SourceDocument{ID: "session", Units: make([]source.SourceUnit, count)}
	input := dnd.NPCOccurrenceList{Occurrences: make([]dnd.NPCOccurrence, count)}
	for index := range doc.Units {
		doc.Units[index].ID = index + 1
		unitID := count - index
		input.Occurrences[index] = occurrence(
			"Ária",
			dnd.NPCOccurrenceKindDialogue,
			source.SourceRef{SourceID: doc.ID, StartUnitID: unitID, EndUnitID: unitID},
		)
	}
	normalizer, err := New(Options{}, npcReferences(t))
	if err != nil {
		t.Fatal(err)
	}
	result, err := normalizer.Normalize(context.Background(), contracts.TypedNormalizeRequest[dnd.NPCOccurrenceList]{
		Source: doc, MergeOutput: contracts.MergeArtifact[dnd.NPCOccurrenceList]{Value: input},
	})
	if err != nil {
		t.Fatal(err)
	}
	if len(result.Diagnostics) == 0 || result.Diagnostics[0].Disposition != contracts.DiagnosticDispositionObservation {
		t.Fatalf("diagnostics = %#v", result.Diagnostics)
	}
}

func occurrence(name string, kind dnd.NPCOccurrenceKind, ref source.SourceRef) dnd.NPCOccurrence {
	return dnd.NPCOccurrence{NPCID: identity.DeriveID(name), Name: name, Kind: kind, SourceRefs: []source.SourceRef{ref}}
}

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}}},
		{ID: identity.DeriveID("Borin"), Name: "Borin", SourceRefs: []source.SourceRef{{SourceID: "registry", StartUnitID: 1, EndUnitID: 1}}},
	}}
	content, err := npccodec.New().Encode(value)
	if err != nil {
		t.Fatalf("encode registry: %v", err)
	}
	return contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{NPCRegistryReferenceSlot: {
		Slot:  contracts.ReferenceSlot{Name: NPCRegistryReferenceSlot, Required: true, AcceptedMediaTypes: []string{npccodec.MediaType}, AcceptedArtifactKinds: []contracts.ArtifactKind{dnd.NPCRegistryKind}, MaxBytes: NPCRegistryMaxBytes},
		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
}
