package shape

import (
	"context"
	"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 TestValidatorApprovesWellFormedCombatTurnList(t *testing.T) {
	result, err := New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.CombatTurnList]{Value: validCombatTurnList()})
	if err != nil || !result.Approved {
		t.Fatalf("Validate() = %#v, %v; want approval without diagnostics", result, err)
	}
}

func TestValidateRejectsEveryOwnedShapeBoundary(t *testing.T) {
	tests := []struct {
		name   string
		mutate func(*dnd.CombatTurnList)
		want   string
	}{
		{name: "missing combat turns", mutate: func(value *dnd.CombatTurnList) { value.CombatTurns = nil }, want: "combat_turns must be present"},
		{name: "empty actor", mutate: func(value *dnd.CombatTurnList) { value.CombatTurns[0].Actor = " " }, want: "actor must not be empty"},
		{name: "unsupported turn kind", mutate: func(value *dnd.CombatTurnList) { value.CombatTurns[0].TurnKind = "unknown" }, want: "turn_kind is unsupported"},
		{name: "missing source refs", mutate: func(value *dnd.CombatTurnList) { value.CombatTurns[0].SourceRefs = nil }, want: "source_refs must contain"},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			value := validCombatTurnList()
			test.mutate(&value)
			if err := Validate(value); 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.CombatTurnList]{Value: value})
			if err != nil || result.Approved || result.ReasonCode != ReasonCode {
				t.Fatalf("Validator result = %#v, %v; want shape rejection", result, err)
			}
			if err := contracts.ValidateValidationResult(result); err != nil {
				t.Fatalf("ValidateValidationResult() error = %v for %#v", err, result)
			}
		})
	}
}

func TestValidatorBoundsAggregateDiagnostics(t *testing.T) {
	value := dnd.CombatTurnList{CombatTurns: make([]dnd.CombatTurn, 30)}
	for index := range value.CombatTurns {
		value.CombatTurns[index].Actor = strings.Repeat("火", 300)
		value.CombatTurns[index].TurnKind = "invalid"
	}
	result, err := New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.CombatTurnList]{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; want safe bounded diagnostics", result, err)
	}
}

func TestSpecRegisterOptionsAndPolicy(t *testing.T) {
	if got := New(Options{}).CheckpointFingerprints(); len(got) != 1 || got[0].Name != "policy" || got[0].Value != policy {
		t.Fatalf("CheckpointFingerprints() = %#v, want shape policy", got)
	}
	if Spec().Key != Key || Spec().ExecutionClass != contracts.ExecutionClassDeterministic {
		t.Fatalf("Spec() = %#v, want deterministic shape validator", 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 validCombatTurnList() dnd.CombatTurnList {
	return dnd.CombatTurnList{CombatTurns: []dnd.CombatTurn{{
		Actor: "Aria", TurnKind: dnd.CombatTurnKindTurn,
		SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 1, EndUnitID: 1}},
	}}}
}
