package combatturns

import (
	"bytes"
	"encoding/json"
	"os"
	"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 validList() dnd.CombatTurnList {
	return dnd.CombatTurnList{CombatTurns: []dnd.CombatTurn{{
		Actor: "Aria", TurnKind: dnd.CombatTurnKindTurn,
		SourceRefs: []source.SourceRef{{SourceID: "session-alpha", StartUnitID: 1, EndUnitID: 2}},
	}}}
}

func TestCodecMatchesMaintainedDurableFixture(t *testing.T) {
	raw, err := os.ReadFile("testdata/dnd_combat_turns.v1.json")
	if err != nil {
		t.Fatal(err)
	}
	codec := New()
	value, err := codec.Decode(raw)
	if err != nil {
		t.Fatalf("Decode() error = %v", err)
	}
	if want := validList(); !reflect.DeepEqual(value, want) {
		t.Fatalf("Decode() = %#v, want %#v", value, want)
	}
	encoded, err := codec.Encode(value)
	if err != nil {
		t.Fatalf("Encode() error = %v", err)
	}
	var compact bytes.Buffer
	if err := json.Compact(&compact, raw); err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, compact.Bytes()) {
		t.Fatalf("Encode() = %s, want %s", encoded, compact.Bytes())
	}
}

func TestCodecOwnsDurableSchemaAndRegistersExactType(t *testing.T) {
	codec := New()
	schema := codec.Schema()
	if codec.Kind() != dnd.CombatTurnListKind || codec.MediaType() != MediaType {
		t.Fatalf("codec identity = %q/%q", codec.Kind(), codec.MediaType())
	}
	if schema.ID != SchemaID || schema.Name != SchemaName || schema.Version != SchemaVersion || !json.Valid(schema.JSONSchema) {
		t.Fatalf("schema = %#v", schema)
	}
	registry := pipeline.NewArtifactCodecRegistry()
	if err := pipeline.RegisterArtifactCodec(registry, codec); err != nil {
		t.Fatal(err)
	}
	spec, ok := registry.Spec(dnd.CombatTurnListKind)
	if !ok || spec.SchemaDigest != contracts.DigestArtifactSchema(schema) {
		t.Fatalf("registered spec = %#v, %t", spec, ok)
	}
}

func TestCodecStrictlyRejectsMalformedUnknownAndInvalidJSON(t *testing.T) {
	validJSON := `{"combat_turns":[{"actor":"Aria","turn_kind":"turn","source_refs":[{"source_id":"session","start_unit_id":1,"end_unit_id":1}]}]}`
	tests := []struct{ name, raw, want string }{
		{"malformed", `{`, "decode dnd combat turn list"},
		{"unknown top-level", `{"combat_turns":[],"unexpected":true}`, "unknown field"},
		{"unknown turn field", strings.Replace(validJSON, `"turn_kind":"turn"`, `"turn_kind":"turn","unexpected":true`, 1), "unknown field"},
		{"unknown source field", strings.Replace(validJSON, `"end_unit_id":1`, `"end_unit_id":1,"unexpected":true`, 1), "unknown field"},
		{"trailing", `{"combat_turns":[]} {}`, "multiple JSON values"},
		{"missing list", `{}`, "combat_turns must be present"},
		{"unsupported kind", strings.Replace(validJSON, `"turn_kind":"turn"`, `"turn_kind":"unsupported"`, 1), "turn_kind must be supported"},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			if _, err := New().Decode([]byte(test.raw)); err == nil || !strings.Contains(err.Error(), test.want) {
				t.Fatalf("Decode() error = %v, want %q", err, test.want)
			}
		})
	}
}

func TestCodecCandidatePreservesValidatorOwnedValuesAndCollectionPresence(t *testing.T) {
	candidates := []dnd.CombatTurnList{
		{},
		{CombatTurns: []dnd.CombatTurn{}},
		{CombatTurns: []dnd.CombatTurn{{Actor: " ", TurnKind: "unsupported", SourceRefs: nil}}},
		{CombatTurns: []dnd.CombatTurn{{Actor: " ", TurnKind: "unsupported", SourceRefs: []source.SourceRef{}}}},
		{CombatTurns: []dnd.CombatTurn{{Actor: " ", TurnKind: "unsupported", SourceRefs: []source.SourceRef{{StartUnitID: 0, EndUnitID: -1}}}}},
	}
	for _, candidate := range candidates {
		content, err := New().EncodeCandidate(candidate)
		if err != nil || !json.Valid(content) {
			t.Fatalf("EncodeCandidate() = %s, %v", content, err)
		}
		decoded, err := New().DecodeCandidate(content)
		if err != nil || !reflect.DeepEqual(decoded, candidate) {
			t.Fatalf("DecodeCandidate() = %#v, %v; want %#v", decoded, err, candidate)
		}
	}
}

func TestCodecRejectsInvalidDurableRangesWhileCandidatesPreserveThem(t *testing.T) {
	codec := New()
	for _, test := range []struct {
		name   string
		mutate func(*dnd.CombatTurnList)
		want   string
	}{
		{name: "nonpositive start", mutate: func(value *dnd.CombatTurnList) { value.CombatTurns[0].SourceRefs[0].StartUnitID = 0 }, want: "start_unit_id"},
		{name: "nonpositive end", mutate: func(value *dnd.CombatTurnList) { value.CombatTurns[0].SourceRefs[0].EndUnitID = 0 }, want: "end_unit_id"},
		{name: "reversed", mutate: func(value *dnd.CombatTurnList) {
			value.CombatTurns[0].SourceRefs[0].StartUnitID = 2
			value.CombatTurns[0].SourceRefs[0].EndUnitID = 1
		}, want: "must not exceed"},
	} {
		t.Run(test.name, func(t *testing.T) {
			candidate := validList()
			test.mutate(&candidate)
			content, err := codec.EncodeCandidate(candidate)
			if err != nil {
				t.Fatalf("EncodeCandidate() error = %v", err)
			}
			decoded, err := codec.DecodeCandidate(content)
			if err != nil || !reflect.DeepEqual(decoded, candidate) {
				t.Fatalf("DecodeCandidate() = %#v, %v; want %#v", decoded, err, candidate)
			}
			if _, err := codec.Encode(candidate); err == nil || !strings.Contains(err.Error(), test.want) {
				t.Fatalf("Encode() error = %v, want %q", err, test.want)
			}
			if _, err := codec.Decode(content); err == nil || !strings.Contains(err.Error(), test.want) {
				t.Fatalf("Decode() error = %v, want %q", err, test.want)
			}
		})
	}
}

func TestCodecRejectsRequiredShapeAndReferenceBoundaries(t *testing.T) {
	tests := []struct {
		name  string
		value dnd.CombatTurnList
		want  string
	}{
		{"nil combat turns", dnd.CombatTurnList{}, "combat_turns must be present"},
		{"empty actor", mutate(validList(), func(v *dnd.CombatTurnList) { v.CombatTurns[0].Actor = " " }), "actor must not be empty"},
		{"unsupported turn kind", mutate(validList(), func(v *dnd.CombatTurnList) { v.CombatTurns[0].TurnKind = "unsupported" }), "turn_kind must be supported"},
		{"nil source refs", mutate(validList(), func(v *dnd.CombatTurnList) { v.CombatTurns[0].SourceRefs = nil }), "source_refs must contain"},
		{"empty source ID", mutate(validList(), func(v *dnd.CombatTurnList) { v.CombatTurns[0].SourceRefs[0].SourceID = " " }), "source_id must not be empty"},
		{"non-positive start", mutate(validList(), func(v *dnd.CombatTurnList) { v.CombatTurns[0].SourceRefs[0].StartUnitID = 0 }), "start_unit_id must be positive"},
		{"non-positive end", mutate(validList(), func(v *dnd.CombatTurnList) { v.CombatTurns[0].SourceRefs[0].EndUnitID = 0 }), "end_unit_id must be positive"},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			if _, err := New().Encode(test.value); err == nil || !strings.Contains(err.Error(), test.want) {
				t.Fatalf("Encode() error = %v, want %q", err, test.want)
			}
		})
	}
}

func TestCodecSchemaAndMetadataAreDefensive(t *testing.T) {
	codec := New()
	first := codec.Schema()
	first.JSONSchema[0] = '['
	if second := codec.Schema(); !json.Valid(second.JSONSchema) || second.JSONSchema[0] == '[' {
		t.Fatal("Schema() returned shared bytes")
	}
	metadata := codec.Metadata(validList())
	metadata["other"] = true
	if next := codec.Metadata(validList()); len(next) != 1 || next["combat_turn_count"] != 1 {
		t.Fatalf("Metadata() = %#v", next)
	}
}

func mutate(value dnd.CombatTurnList, change func(*dnd.CombatTurnList)) dnd.CombatTurnList {
	change(&value)
	return value
}
