package enemyevents

import (
	"bytes"
	"encoding/json"
	"strings"
	"testing"

	"github.com/santhosh-tekuri/jsonschema/v6"

	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
)

func TestResponseSchemaDefinesPrivateStructuralBoundary(t *testing.T) {
	schema, err := loadResponseSchema()
	if err != nil {
		t.Fatal(err)
	}
	if schema.Key != ResponseSchemaKey || schema.ID != ResponseSchemaID || schema.Name != ResponseSchemaName || schema.Version != SchemaVersion || !strings.HasPrefix(schema.SHA256, "sha256:") || !json.Valid(schema.JSONSchema) {
		t.Fatalf("schema = %#v", schema)
	}
	valid := validEnemyResponse()
	content, err := json.Marshal(valid)
	if err != nil {
		t.Fatal(err)
	}
	if err := validateEnemySchema(content, schema.JSONSchema); err != nil {
		t.Fatalf("valid response rejected: %v", err)
	}
	semantic := validEnemyResponse()
	event := semantic["events"].([]any)[0].(map[string]any)
	event["name"] = ""
	ref := event["source_refs"].([]any)[0].(map[string]any)
	ref["start_unit_id"] = 0
	ref["end_unit_id"] = -1
	content, err = json.Marshal(semantic)
	if err != nil || validateEnemySchema(content, schema.JSONSchema) != nil {
		t.Fatalf("non-categorical validator-owned semantics were rejected: %v", err)
	}
}

func TestResponseSchemaRejectsInvalidStructure(t *testing.T) {
	schema, err := loadResponseSchema()
	if err != nil {
		t.Fatal(err)
	}
	for _, mutate := range []func(map[string]any){
		func(event map[string]any) { delete(event, "name") },
		func(event map[string]any) { event["kind"] = 1 },
		func(event map[string]any) { event["kind"] = "unsupported" },
		func(event map[string]any) { event["unexpected"] = true },
		func(event map[string]any) { event["source_refs"].([]any)[0].(map[string]any)["source_id"] = "session" },
	} {
		candidate := validEnemyResponse()
		mutate(candidate["events"].([]any)[0].(map[string]any))
		content, err := json.Marshal(candidate)
		if err != nil {
			t.Fatal(err)
		}
		if err := validateEnemySchema(content, schema.JSONSchema); err == nil {
			t.Fatal("private schema accepted structurally invalid response")
		}
	}
	first, err := loadResponseSchema()
	if err != nil {
		t.Fatal(err)
	}
	first.JSONSchema[0] = '['
	second, err := loadResponseSchema()
	if err != nil || !json.Valid(second.JSONSchema) || bytes.Equal(first.JSONSchema, second.JSONSchema) {
		t.Fatalf("schema defensive copy = %s, %v", second.JSONSchema, err)
	}
}

func TestResponseSchemaAcceptsEverySupportedKind(t *testing.T) {
	schema, err := loadResponseSchema()
	if err != nil {
		t.Fatal(err)
	}
	for _, kind := range []string{string(dnd.EnemyEventKindEngaged), string(dnd.EnemyEventKindKilled), string(dnd.EnemyEventKindFled), string(dnd.EnemyEventKindCaptured), string(dnd.EnemyEventKindIncapacitated)} {
		candidate := validEnemyResponse()
		candidate["events"].([]any)[0].(map[string]any)["kind"] = kind
		content, err := json.Marshal(candidate)
		if err != nil {
			t.Fatal(err)
		}
		if err := validateEnemySchema(content, schema.JSONSchema); err != nil {
			t.Fatalf("supported enemy-event kind %q was rejected: %v", kind, err)
		}
	}
}

func validEnemyResponse() map[string]any {
	return map[string]any{"events": []any{map[string]any{
		"name": "Ashfang", "kind": "engaged", "source_refs": []any{map[string]any{"start_unit_id": 1, "end_unit_id": 1}},
	}}}
}

func validateEnemySchema(instanceContent, schemaContent []byte) error {
	instance, err := jsonschema.UnmarshalJSON(bytes.NewReader(instanceContent))
	if err != nil {
		return err
	}
	document, err := jsonschema.UnmarshalJSON(bytes.NewReader(schemaContent))
	if err != nil {
		return err
	}
	compiler := jsonschema.NewCompiler()
	if err := compiler.AddResource("schema.json", document); err != nil {
		return err
	}
	schema, err := compiler.Compile("schema.json")
	if err != nil {
		return err
	}
	return schema.Validate(instance)
}
