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

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.Diagnostics) != 0 {
		t.Fatalf("cited match = %#v, %v; want approval without advisories", 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.Diagnostics) != 1 || result.Diagnostics[0].ReasonCode != ReasonCode || !strings.Contains(result.Diagnostics[0].Samples[0].Message, "Glossary Keep") || !reflect.DeepEqual(value, before) {
		t.Fatalf("reference-only match = %#v, %v; want advisory", 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.Diagnostics) != 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.Diagnostics) != 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 TestValidatorBoundsAdvisories(t *testing.T) {
	locations := make([]dnd.Location, contracts.MaxDiagnosticSamples+2)
	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.Diagnostics) != 1 || result.Diagnostics[0].OccurrenceCount != len(locations) || len(result.Diagnostics[0].Samples) != contracts.MaxDiagnosticSamples {
		t.Fatalf("bounded advisories = %#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."}}}
}
