package invariants

import (
	"context"
	"reflect"
	"strings"
	"testing"
	"unicode/utf8"

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

func TestValidatorApprovesNormalizedOutput(t *testing.T) {
	doc := invariantDocument()
	result, err := New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.ItemOccurrenceList]{Source: doc, Value: normalizedList()})
	if err != nil || !result.Approved {
		t.Fatalf("Validate() = %#v, %v; want approval", result, err)
	}
}

func TestValidateRejectsOwnedNormalizedInvariants(t *testing.T) {
	tests := []struct {
		name   string
		mutate func(*dnd.ItemOccurrenceList)
		want   string
	}{
		{name: "name whitespace", mutate: func(value *dnd.ItemOccurrenceList) { value.Occurrences[0].Name = " Coin " }, want: ".name is not display-normalized"},
		{name: "from whitespace", mutate: func(value *dnd.ItemOccurrenceList) {
			value.Occurrences[0].Kind = dnd.ItemOccurrenceKindLost
			value.Occurrences[0].From = " Aria "
		}, want: ".from is not display-normalized"},
		{name: "to whitespace", mutate: func(value *dnd.ItemOccurrenceList) {
			value.Occurrences[0].Kind = dnd.ItemOccurrenceKindAcquired
			value.Occurrences[0].To = " Aria "
		}, want: ".to is not display-normalized"},
		{name: "reference order", mutate: func(value *dnd.ItemOccurrenceList) {
			value.Occurrences[0].SourceRefs = []source.SourceRef{{SourceID: "session", StartUnitID: 20, EndUnitID: 20}, {SourceID: "session", StartUnitID: 10, EndUnitID: 10}}
		}, want: "not in canonical order"},
		{name: "duplicate reference", mutate: func(value *dnd.ItemOccurrenceList) {
			value.Occurrences[0].SourceRefs = append(value.Occurrences[0].SourceRefs, value.Occurrences[0].SourceRefs[0])
		}, want: "duplicates the previous reference"},
		{name: "list order", mutate: func(value *dnd.ItemOccurrenceList) {
			value.Occurrences = []dnd.ItemOccurrence{value.Occurrences[1], value.Occurrences[0]}
		}, want: "out of canonical order"},
		{name: "duplicate occurrence", mutate: func(value *dnd.ItemOccurrenceList) {
			value.Occurrences = append(value.Occurrences, value.Occurrences[0])
		}, want: "duplicates item occurrence"},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			value := normalizedList()
			test.mutate(&value)
			err := Validate(invariantDocument(), value)
			if err == nil || !strings.Contains(err.Error(), test.want) {
				t.Fatalf("Validate() error = %v, want %q", err, test.want)
			}
			result, err := New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.ItemOccurrenceList]{Source: invariantDocument(), Value: value})
			if err != nil || result.Approved || result.ReasonCode != ReasonCode {
				t.Fatalf("validator result = %#v, %v", result, err)
			}
		})
	}
}

func TestValidateUsesSourceDocumentOrderAndDefersEarlierFailures(t *testing.T) {
	doc := &source.SourceDocument{ID: "session", Units: []source.SourceUnit{{ID: 30}, {ID: 10}}}
	value := dnd.ItemOccurrenceList{Occurrences: []dnd.ItemOccurrence{{
		ItemID: "item", Name: "Coin", Kind: dnd.ItemOccurrenceKindDiscovered,
		SourceRefs: []source.SourceRef{{SourceID: doc.ID, StartUnitID: 10, EndUnitID: 10}, {SourceID: doc.ID, StartUnitID: 30, EndUnitID: 30}},
	}}}
	if err := Validate(doc, value); err == nil || !strings.Contains(err.Error(), "not in canonical order") {
		t.Fatalf("Validate() error = %v, want document-order rejection", err)
	}
	shapeInvalid := normalizedList()
	shapeInvalid.Occurrences[0].Name = " "
	if err := Validate(invariantDocument(), shapeInvalid); err != nil {
		t.Fatalf("shape failure must be deferred, got %v", err)
	}
	sourceInvalid := normalizedList()
	sourceInvalid.Occurrences[0].SourceRefs[0].StartUnitID = 999
	if err := Validate(invariantDocument(), sourceInvalid); err != nil {
		t.Fatalf("source-reference failure must be deferred, got %v", err)
	}
}

func TestValidatorContractAndBoundedDiagnostics(t *testing.T) {
	value := normalizedList()
	value.Occurrences = make([]dnd.ItemOccurrence, 30)
	for index := range value.Occurrences {
		value.Occurrences[index] = normalizedList().Occurrences[0]
		value.Occurrences[index].Name = strings.Repeat("火", 300)
	}
	result, err := New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.ItemOccurrenceList]{Source: invariantDocument(), Value: value})
	if err != nil || result.Approved || !utf8.ValidString(result.Message) || len([]byte(result.Message)) > 4096 || !strings.Contains(result.Message, "additional issue(s) omitted") {
		t.Fatalf("bounded result = %#v, %v", result, err)
	}
	if got := New(Options{}).CheckpointFingerprints(); !reflect.DeepEqual(got, []pipeline.CheckpointFingerprint{{Name: "policy", Value: policy}}) {
		t.Fatalf("CheckpointFingerprints() = %#v", got)
	}
	if spec := Spec(); spec.Key != Key || spec.ExecutionClass != contracts.ExecutionClassDeterministic {
		t.Fatalf("Spec() = %#v", spec)
	}
	registry := pipeline.NewValidatorRegistry()
	if err := Register(registry); err != nil {
		t.Fatalf("Register() error = %v", err)
	}
	if _, err := DecodeOptions(map[string]any{"unexpected": true}); err == nil {
		t.Fatal("DecodeOptions() accepted unknown option")
	}
}

func normalizedList() dnd.ItemOccurrenceList {
	return dnd.ItemOccurrenceList{Occurrences: []dnd.ItemOccurrence{{ItemID: "item", Name: "Arrow", Kind: dnd.ItemOccurrenceKindDiscovered, SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 10, EndUnitID: 10}}},
		{ItemID: "item", Name: "Coin", Kind: dnd.ItemOccurrenceKindDiscovered, SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 20, EndUnitID: 20}}},
	}}
}

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