package sourcerefs

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 TestValidatorRejectsInvalidAndOutOfChunkReferencesWithoutMutation(t *testing.T) {
	value := validItemRegistry()
	value.Items[0].SourceRefs = []source.SourceRef{{SourceID: "foreign", StartUnitID: 1, EndUnitID: 1}}
	before := value
	result, err := New(Options{}).Validate(context.Background(), request(validDocument(), value))
	if err != nil || result.Approved || result.ReasonCode != ReasonCode || !strings.Contains(result.Message, "items[0].source_refs[0]") || !reflect.DeepEqual(value, before) {
		t.Fatalf("Validate() = %#v, %v; want source-reference rejection", result, err)
	}
	doc := &source.SourceDocument{ID: "session", Units: []source.SourceUnit{{ID: 1}, {ID: 2}}}
	value = validItemRegistry()
	value.Items[0].SourceRefs[0].EndUnitID = 2
	result, err = New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.ItemRegistry]{Stage: string(pipeline.StageExtract), Source: doc, Chunk: &source.Chunk{SourceID: "session", Units: []source.SourceUnit{{ID: 1}}}, Value: value})
	if err != nil || result.Approved || !strings.Contains(result.Message, "outside the current extraction chunk") {
		t.Fatalf("out-of-chunk evidence = %#v, %v", result, err)
	}
}

func TestValidatorDefersMalformedShapeAndRegisters(t *testing.T) {
	result, err := New(Options{}).Validate(context.Background(), request(nil, dnd.ItemRegistry{Items: []dnd.Item{{Name: "Missing"}}}))
	if err != nil || !result.Approved {
		t.Fatalf("malformed shape = %#v, %v; want deferral", result, err)
	}
	_, err = New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.ItemRegistry]{Stage: string(pipeline.StageExtract), Source: validDocument(), Value: validItemRegistry()})
	if err == nil || !strings.Contains(err.Error(), "requires the current extraction chunk") {
		t.Fatalf("missing chunk error = %v", err)
	}
	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)
	}
}

func TestValidatorRequiresEveryUnitInCitedSpanToBeInChunk(t *testing.T) {
	doc := &source.SourceDocument{ID: "session", Units: []source.SourceUnit{{ID: 30}, {ID: 10}, {ID: 20}}}
	value := validItemRegistry()
	value.Items[0].SourceRefs = []source.SourceRef{{SourceID: doc.ID, StartUnitID: 30, EndUnitID: 20}}
	chunk := &source.Chunk{SourceID: doc.ID, Units: []source.SourceUnit{{ID: 30}, {ID: 20}}}
	result, err := New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.ItemRegistry]{Stage: string(pipeline.StageExtract), Source: doc, Chunk: chunk, Value: value})
	if err != nil || result.Approved || !strings.Contains(result.Message, "outside the current extraction chunk") {
		t.Fatalf("Validate() = %#v, %v; want missing-middle-unit rejection", result, err)
	}
}

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

func validDocument() *source.SourceDocument {
	return &source.SourceDocument{ID: "session", Units: []source.SourceUnit{{ID: 1, Text: "The party finds rope."}}}
}

func validItemRegistry() dnd.ItemRegistry {
	return dnd.ItemRegistry{Items: []dnd.Item{{ID: "item", Name: "Rope", SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 1, EndUnitID: 1}}}}}
}
