package npcoccurrences

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

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

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

func TestResponseSchemaOwnsOnlyPrivateStructuralContract(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 := validOccurrenceResponse()
	content, err := json.Marshal(valid)
	if err != nil {
		t.Fatal(err)
	}
	if err := validateJSONSchema(content, schema.JSONSchema); err != nil {
		t.Fatalf("valid response rejected: %v", err)
	}

	semanticCandidate := validOccurrenceResponse()
	occurrence := semanticCandidate["occurrences"].([]any)[0].(map[string]any)
	occurrence["name"] = ""
	ref := occurrence["source_refs"].([]any)[0].(map[string]any)
	ref["start_unit_id"] = 0
	ref["end_unit_id"] = -1
	content, err = json.Marshal(semanticCandidate)
	if err != nil {
		t.Fatal(err)
	}
	if err := validateJSONSchema(content, schema.JSONSchema); err != nil {
		t.Fatalf("schema rejected non-categorical validator-owned semantics: %v", err)
	}

	for _, mutate := range []func(map[string]any){
		func(record map[string]any) { delete(record, "name") },
		func(record map[string]any) { record["kind"] = 1 },
		func(record map[string]any) { record["kind"] = "unsupported" },
		func(record map[string]any) { record["npc_id"] = "npc:sha256:opaque" },
		func(record map[string]any) { record["unexpected"] = true },
		func(record map[string]any) {
			record["source_refs"].([]any)[0].(map[string]any)["source_id"] = "assigned later"
		},
	} {
		candidate := validOccurrenceResponse()
		mutate(candidate["occurrences"].([]any)[0].(map[string]any))
		content, err := json.Marshal(candidate)
		if err != nil {
			t.Fatal(err)
		}
		if err := validateJSONSchema(content, schema.JSONSchema); err == nil {
			t.Fatal("schema accepted structurally invalid response")
		}
	}
}

func TestResponseSchemaIsDefensiveAndContentSafe(t *testing.T) {
	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("second schema = %s, %v", second.JSONSchema, err)
	}
	if diagnostics := second.DiagnosticsMap(); diagnostics["key"] != ResponseSchemaKey || diagnostics["id"] != ResponseSchemaID {
		t.Fatalf("diagnostics = %#v", diagnostics)
	} else if _, ok := diagnostics["json_schema"]; ok {
		t.Fatalf("diagnostics leak schema content: %#v", diagnostics)
	}
}

func TestResponseSchemaAcceptsEverySupportedKind(t *testing.T) {
	schema, err := loadResponseSchema()
	if err != nil {
		t.Fatal(err)
	}
	for _, kind := range []string{string(dnd.NPCOccurrenceKindMentioned), string(dnd.NPCOccurrenceKindNoncombatPresence), string(dnd.NPCOccurrenceKindDialogue), string(dnd.NPCOccurrenceKindCombatAlly), string(dnd.NPCOccurrenceKindCombatOpponent), string(dnd.NPCOccurrenceKindOther)} {
		candidate := validOccurrenceResponse()
		candidate["occurrences"].([]any)[0].(map[string]any)["kind"] = kind
		content, err := json.Marshal(candidate)
		if err != nil {
			t.Fatal(err)
		}
		if err := validateJSONSchema(content, schema.JSONSchema); err != nil {
			t.Fatalf("supported NPC-occurrence kind %q was rejected: %v", kind, err)
		}
	}
}

func validOccurrenceResponse() map[string]any {
	return map[string]any{"occurrences": []any{map[string]any{
		"name": "Mira Thorn", "kind": "dialogue",
		"source_refs": []any{map[string]any{"start_unit_id": 1, "end_unit_id": 2}},
	}}}
}

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