package scenedescriptions

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

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

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

func TestLoadResponseSchemaUsesStrictPrivateSceneDescriptionContract(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 scene-description schema identity", schema)
	}
	valid := map[string]any{"kind": "narrative", "title": "Arrival", "summary": "The party enters the tower."}
	if err := validateJSONSchema(t, valid, schema.JSONSchema); err != nil {
		t.Fatalf("valid private response rejected: %v", err)
	}
	for _, test := range []struct {
		name     string
		response map[string]any
		valid    bool
	}{
		{name: "missing required field", response: map[string]any{"kind": "combat", "title": "Ambush"}},
		{name: "unknown framework field", response: map[string]any{"kind": "combat", "title": "Ambush", "summary": "Bandits strike.", "id": "assigned-later"}},
		{name: "unknown application field", response: map[string]any{"kind": "combat", "title": "Ambush", "summary": "Bandits strike.", "source_ref": map[string]any{}}},
		{name: "collection is not allowed", response: map[string]any{"kind": "combat", "title": "Ambush", "summary": "Bandits strike.", "scenes": []any{}}},
		{name: "unsupported kind", response: map[string]any{"kind": "interlude", "title": "Ambush", "summary": "Bandits strike."}},
		{name: "empty title", response: map[string]any{"kind": "combat", "title": "", "summary": "Bandits strike."}, valid: true},
		{name: "empty summary", response: map[string]any{"kind": "combat", "title": "Ambush", "summary": ""}, valid: true},
		{name: "wrong kind type", response: map[string]any{"kind": 7, "title": "Ambush", "summary": "Bandits strike."}},
		{name: "wrong title type", response: map[string]any{"kind": "combat", "title": 7, "summary": "Bandits strike."}},
		{name: "wrong summary type", response: map[string]any{"kind": "combat", "title": "Ambush", "summary": 7}},
	} {
		t.Run(test.name, func(t *testing.T) {
			err := validateJSONSchema(t, test.response, schema.JSONSchema)
			if (err == nil) != test.valid {
				t.Fatalf("validateJSONSchema() error = %v, want valid=%t", err, test.valid)
			}
		})
	}
	if err := validateJSONSchemaContent([]byte(`{"kind":`), schema.JSONSchema); err == nil {
		t.Fatal("validateJSONSchemaContent() error = nil, want malformed JSON rejected")
	}
}

func TestResponseSchemaIsMutationSafeAndDiagnosticsRedactContent(t *testing.T) {
	first, err := loadResponseSchema()
	if err != nil {
		t.Fatal(err)
	}
	first.JSONSchema[0] = '['
	second, err := loadResponseSchema()
	if err != nil || !strings.HasPrefix(second.SHA256, "sha256:") || !json.Valid(second.JSONSchema) || bytes.Equal(first.JSONSchema, second.JSONSchema) {
		t.Fatalf("second schema = %s, %v; want defensive copy", second.JSONSchema, err)
	}
	if diagnostics := second.DiagnosticsMap(); diagnostics["json_schema"] != nil {
		t.Fatalf("schema diagnostics included raw content: %#v", diagnostics)
	}
}

func TestResponseSchemaAcceptsEverySupportedKind(t *testing.T) {
	schema, err := loadResponseSchema()
	if err != nil {
		t.Fatal(err)
	}
	for _, kind := range []string{string(dnd.SceneKindCombat), string(dnd.SceneKindNarrative), string(dnd.SceneKindRecap), string(dnd.SceneKindMeta)} {
		response := map[string]any{"kind": kind, "title": "Title", "summary": "Summary"}
		if err := validateJSONSchema(t, response, schema.JSONSchema); err != nil {
			t.Fatalf("supported scene kind %q was rejected: %v", kind, err)
		}
	}
}

func validateJSONSchema(t *testing.T, instance map[string]any, schemaContent []byte) error {
	t.Helper()
	content, err := json.Marshal(instance)
	if err != nil {
		t.Fatal(err)
	}
	return validateJSONSchemaContent(content, schemaContent)
}

func validateJSONSchemaContent(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)
}
