package npcregistry

import (
	"embed"
	"fmt"
	"strings"

	"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/candidatejson"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/sourcerange"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/npcs/identity"
)

const (
	SchemaID      = "notarius.dnd.npc_registry"
	SchemaName    = "notarius_dnd_npc_registry_v1"
	SchemaVersion = "v1"
	MediaType     = "application/json"
)

//go:embed assets/schemas/dnd_npc_registry.v1.json
var schemaAssets embed.FS

var _ contracts.ArtifactCodec[dnd.NPCRegistry] = (*Codec)(nil)
var _ contracts.CandidateArtifactCodec[dnd.NPCRegistry] = (*Codec)(nil)

type Codec struct{}

func New() *Codec { return &Codec{} }

func (c *Codec) Kind() contracts.ArtifactKind { return dnd.NPCRegistryKind }

func (c *Codec) Schema() contracts.ArtifactSchema {
	raw, err := schemaAssets.ReadFile("assets/schemas/dnd_npc_registry.v1.json")
	if err != nil {
		return contracts.ArtifactSchema{}
	}
	return contracts.ArtifactSchema{
		ID:         SchemaID,
		Name:       SchemaName,
		Version:    SchemaVersion,
		JSONSchema: append([]byte(nil), raw...),
	}
}

func (c *Codec) MediaType() string { return MediaType }

func (c *Codec) Metadata(value dnd.NPCRegistry) map[string]any {
	return map[string]any{"npc_count": len(value.NPCs)}
}

func (c *Codec) Encode(value dnd.NPCRegistry) ([]byte, error) {
	if err := validate(value); err != nil {
		return nil, fmt.Errorf("encode dnd npc registry: %w", err)
	}
	return c.EncodeCandidate(value)
}

// EncodeCandidate provides the durable representation before semantic
// validators have approved a value.
func (c *Codec) EncodeCandidate(value dnd.NPCRegistry) ([]byte, error) {
	return candidatejson.EncodeCandidate("dnd npc registry", value)
}

func (c *Codec) Decode(content []byte) (dnd.NPCRegistry, error) {
	value, err := c.DecodeCandidate(content)
	if err != nil {
		return dnd.NPCRegistry{}, err
	}
	if err := validate(value); err != nil {
		return dnd.NPCRegistry{}, fmt.Errorf("decode dnd npc registry: %w", err)
	}
	return value, nil
}

// DecodeCandidate reads one strict durable JSON value before semantic
// validators have approved it.
func (c *Codec) DecodeCandidate(content []byte) (dnd.NPCRegistry, error) {
	return candidatejson.DecodeCandidate[dnd.NPCRegistry]("dnd npc registry", content)
}

func validate(value dnd.NPCRegistry) error {
	if value.NPCs == nil {
		return fmt.Errorf("npcs must be present")
	}
	for index, npc := range value.NPCs {
		prefix := fmt.Sprintf("npcs[%d]", index)
		if !identity.IsValidID(npc.ID) {
			return fmt.Errorf("%s.id must match npc ID pattern", prefix)
		}
		if strings.TrimSpace(npc.Name) == "" {
			return fmt.Errorf("%s.name must not be empty", prefix)
		}
		if len(npc.SourceRefs) == 0 {
			return fmt.Errorf("%s.source_refs must not be empty", prefix)
		}
		for refIndex, ref := range npc.SourceRefs {
			refPrefix := fmt.Sprintf("%s.source_refs[%d]", prefix, refIndex)
			if strings.TrimSpace(ref.SourceID) == "" {
				return fmt.Errorf("%s.source_id must not be empty", refPrefix)
			}
			if err := sourcerange.Validate(ref); err != nil {
				return fmt.Errorf("%s: %w", refPrefix, err)
			}
		}
	}
	return nil
}
