package sourcerelatedness

import (
	"context"
	"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"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared/diagnostics"
)

func TestValidatorUsesOnlyCitedTranscriptText(t *testing.T) {
	value := dnd.LocationRegistry{Locations: []dnd.Location{{ID: "candidate", Name: "O'Rin's Gate", SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 1, EndUnitID: 1}}}}}
	doc := &source.SourceDocument{ID: "session", Kind: "transcript", Format: "application/json", Digest: "sha256:session", Units: []source.SourceUnit{{ID: 1, Kind: "message", Text: "The party enters o’rin’s gate."}, {ID: 2, Kind: "message", Text: "Unrelated location."}}}
	result, err := New(Options{}).Validate(context.Background(), request(doc, value, contracts.ReferenceSet{}))
	if err != nil || !result.Approved || len(result.Warnings) != 0 {
		t.Fatalf("cited match = %#v, %v; want approval without warnings", result, err)
	}
	value.Locations[0].Name = "Glossary Keep"
	before := value
	references := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{"glossary": {Items: []contracts.ReferenceItem{{Content: []byte("Glossary Keep")}}}}}
	result, err = New(Options{}).Validate(context.Background(), request(doc, value, references))
	if err != nil || !result.Approved || len(result.Warnings) != 1 || result.Warnings[0].ReasonCode != WarningReasonCode || !strings.Contains(result.Warnings[0].Message, "Glossary Keep") || !reflect.DeepEqual(value, before) {
		t.Fatalf("reference-only match = %#v, %v; want advisory warning", result, err)
	}
}

func TestValidatorDefersMalformedOrUnreadableCitations(t *testing.T) {
	invalid := dnd.LocationRegistry{Locations: []dnd.Location{{Name: "Missing"}}}
	result, err := New(Options{}).Validate(context.Background(), request(document(), invalid, contracts.ReferenceSet{}))
	if err != nil || !result.Approved || len(result.Warnings) != 0 {
		t.Fatalf("shape deferral = %#v, %v", result, err)
	}
	value := dnd.LocationRegistry{Locations: []dnd.Location{{ID: "candidate", Name: "Missing", SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 99, EndUnitID: 99}}}}}
	result, err = New(Options{}).Validate(context.Background(), request(document(), value, contracts.ReferenceSet{}))
	if err != nil || !result.Approved || len(result.Warnings) != 0 {
		t.Fatalf("unreadable citation = %#v, %v", result, err)
	}
}

func TestValidatorRegisters(t *testing.T) {
	registry := pipeline.NewValidatorRegistry()
	if err := Register(registry); err != nil {
		t.Fatalf("Register() error = %v", err)
	}
	if got, ok := registry.Spec(Key); !ok || got != Spec() || got.ExecutionClass != contracts.ExecutionClassDeterministic {
		t.Fatalf("registered spec = %#v, ok = %t", got, ok)
	}
	if got := New(Options{}).CheckpointFingerprints(); len(got) != 1 || got[0].Value != policy {
		t.Fatalf("fingerprints = %#v", got)
	}
}

func TestValidatorBoundsWarnings(t *testing.T) {
	locations := make([]dnd.Location, diagnostics.MaxWarnings+1)
	for index := range locations {
		locations[index] = dnd.Location{ID: "candidate", Name: "Missing", SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 1, EndUnitID: 1}}}
	}
	result, err := New(Options{}).Validate(context.Background(), request(document(), dnd.LocationRegistry{Locations: locations}, contracts.ReferenceSet{}))
	if err != nil || !result.Approved || len(result.Warnings) != diagnostics.MaxWarnings || result.Warnings[len(result.Warnings)-1].ReasonCode != OmittedReasonCode {
		t.Fatalf("bounded warnings = %#v, %v", result, err)
	}
}

func request(doc *source.SourceDocument, value dnd.LocationRegistry, references contracts.ReferenceSet) contracts.TypedValidationRequest[dnd.LocationRegistry] {
	return contracts.TypedValidationRequest[dnd.LocationRegistry]{Source: doc, References: references, Value: value}
}

func document() *source.SourceDocument {
	return &source.SourceDocument{ID: "session", Kind: "transcript", Format: "application/json", Digest: "sha256:session", Units: []source.SourceUnit{{ID: 1, Kind: "message", Text: "The party waits."}}}
}
