package npcregistry

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

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

func TestLoadResponseSchemaUsesPrivateNPCSchema(t *testing.T) {
	schema, err := loadResponseSchema()
	if err != nil {
		t.Fatalf("loadResponseSchema() error = %v, want nil", err)
	}
	if schema.Key != ResponseSchemaKey || schema.ID != ResponseSchemaID || schema.Version != SchemaVersion || schema.Name != ResponseSchemaName || !strings.HasPrefix(schema.SHA256, "sha256:") || !json.Valid(schema.JSONSchema) {
		t.Fatalf("schema = %#v, want private NPC schema identity", schema)
	}
	valid := map[string]any{"npcs": []any{map[string]any{
		"name":        "Mira Thorn",
		"source_refs": []any{map[string]any{"start_unit_id": 1, "end_unit_id": 2}},
	}}}
	validJSON, err := json.Marshal(valid)
	if err != nil {
		t.Fatal(err)
	}
	if err := validateJSONSchema(validJSON, schema.JSONSchema); err != nil {
		t.Fatalf("valid private NPC response rejected: %v", err)
	}
	for _, test := range []struct {
		name     string
		response map[string]any
		valid    bool
	}{
		{
			name: "semantic blanks and empty collections",
			response: map[string]any{"npcs": []any{map[string]any{
				"name": "", "source_refs": []any{},
			}}},
			valid: true,
		},
		{
			name: "nonpositive unit candidates",
			response: map[string]any{"npcs": []any{map[string]any{
				"name":        "Mira Thorn",
				"source_refs": []any{map[string]any{"start_unit_id": 0, "end_unit_id": -1}},
			}}},
			valid: true,
		},
		{
			name: "missing required field",
			response: map[string]any{"npcs": []any{map[string]any{
				"source_refs": []any{},
			}}},
		},
		{
			name: "unknown field",
			response: map[string]any{"npcs": []any{map[string]any{
				"name": "Mira Thorn", "source_refs": []any{}, "id": "assigned later",
			}}},
		},
		{
			name: "wrong field type",
			response: map[string]any{"npcs": []any{map[string]any{
				"name": 7, "source_refs": []any{},
			}}},
		},
		{
			name: "noninteger source identifier",
			response: map[string]any{"npcs": []any{map[string]any{
				"name":        "Mira Thorn",
				"source_refs": []any{map[string]any{"start_unit_id": 1.5, "end_unit_id": 2}},
			}}},
		},
	} {
		t.Run(test.name, func(t *testing.T) {
			content, err := json.Marshal(test.response)
			if err != nil {
				t.Fatal(err)
			}
			err = validateJSONSchema(content, schema.JSONSchema)
			if (err == nil) != test.valid {
				t.Fatalf("validateJSONSchema() error = %v, want valid=%t", err, test.valid)
			}
		})
	}
	if err := validateJSONSchema([]byte(`{"npcs":`), schema.JSONSchema); err == nil {
		t.Fatal("validateJSONSchema() error = nil, want malformed JSON rejected")
	}
	withID := map[string]any{"npcs": []any{map[string]any{
		"name": "Mira Thorn", "id": "assigned-later",
		"source_refs": []any{map[string]any{"start_unit_id": 1, "end_unit_id": 2}},
	}}}
	withIDJSON, err := json.Marshal(withID)
	if err != nil {
		t.Fatal(err)
	}
	if err := validateJSONSchema(withIDJSON, schema.JSONSchema); err == nil {
		t.Fatal("private schema accepted framework-assigned id")
	}
}

func TestResponseSchemaIsMutationSafeAndDiagnosticsRedactContent(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; want defensive copy", second.JSONSchema, err)
	}
	diagnostics := second.DiagnosticsMap()
	if _, ok := diagnostics["json_schema"]; ok {
		t.Fatalf("schema diagnostics included raw content: %#v", diagnostics)
	}
}

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
	}
	compiled, err := compiler.Compile("schema.json")
	if err != nil {
		return err
	}
	return compiled.Validate(instance)
}
