package sourcerefs

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 TestValidatorRejectsForeignAndOutOfRangeReferencesWithoutMutation(t *testing.T) {
	value := validLocationRegistry()
	value.Locations[0].SourceRefs = []source.SourceRef{{SourceID: "foreign", StartUnitID: 1, EndUnitID: 1}, {SourceID: "session", StartUnitID: 9, EndUnitID: 9}}
	before := value
	result, err := New(Options{}).Validate(context.Background(), request(validDocument(), value))
	if err != nil || result.Approved || result.ReasonCode != ReasonCode || !strings.Contains(result.Message, "locations[0].source_refs[0]") {
		t.Fatalf("Validate() = %#v, %v; want source-reference rejection", result, err)
	}
	if len(result.Message) > 4096 || !utf8.ValidString(result.Message) || !reflect.DeepEqual(value, before) {
		t.Fatalf("Validate() produced unsafe diagnostics or mutated value")
	}
}

func TestValidatorApprovesValidReferencesAndDefersMalformedShape(t *testing.T) {
	result, err := New(Options{}).Validate(context.Background(), request(validDocument(), validLocationRegistry()))
	if err != nil || !result.Approved {
		t.Fatalf("valid references = %#v, %v", result, err)
	}
	result, err = New(Options{}).Validate(context.Background(), request(nil, dnd.LocationRegistry{Locations: []dnd.Location{{Name: "Missing"}}}))
	if err != nil || !result.Approved || result.ReasonCode != "" {
		t.Fatalf("malformed shape = %#v, %v; want deferral", result, err)
	}
}

func TestValidatorRequiresCurrentChunkAndRejectsEvidenceOutsideIt(t *testing.T) {
	doc := &source.SourceDocument{ID: "session", Units: []source.SourceUnit{{ID: 1}, {ID: 2}}}
	value := validLocationRegistry()
	result, err := New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.LocationRegistry]{
		Stage: string(pipeline.StageExtract), Source: doc,
		Chunk: &source.Chunk{SourceID: "session", Units: []source.SourceUnit{{ID: 1}}}, Value: value,
	})
	if err != nil || !result.Approved {
		t.Fatalf("contained extraction evidence = %#v, %v", result, err)
	}
	value.Locations[0].SourceRefs[0].EndUnitID = 2
	result, err = New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.LocationRegistry]{
		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 extraction evidence = %#v, %v", result, err)
	}
	_, err = New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.LocationRegistry]{Stage: string(pipeline.StageExtract), Source: doc, Value: validLocationRegistry()})
	if err == nil || !strings.Contains(err.Error(), "requires the current extraction chunk") {
		t.Fatalf("missing chunk error = %v", 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 request(doc *source.SourceDocument, value dnd.LocationRegistry) contracts.TypedValidationRequest[dnd.LocationRegistry] {
	return contracts.TypedValidationRequest[dnd.LocationRegistry]{Source: doc, Value: value}
}

func validDocument() *source.SourceDocument {
	return &source.SourceDocument{ID: "session", Kind: "transcript", Format: "application/json", Digest: "sha256:session", Units: []source.SourceUnit{{ID: 1, Kind: "message", Text: "Moon Gate opens."}}}
}

func validLocationRegistry() dnd.LocationRegistry {
	return dnd.LocationRegistry{Locations: []dnd.Location{{ID: "candidate", Name: "Moon Gate", SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 1, EndUnitID: 1}}}}}
}
