package scenedescriptions

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"
)

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

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

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

type Codec struct{}

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

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

func (c *Codec) Schema() contracts.ArtifactSchema {
	raw, err := schemaAssets.ReadFile("assets/schemas/dnd_scene_descriptions.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.SceneDescriptionList) map[string]any {
	return map[string]any{"scene_count": len(value.Scenes)}
}

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

// EncodeCandidate provides the durable representation before typed validators
// have approved a value.
func (c *Codec) EncodeCandidate(value dnd.SceneDescriptionList) ([]byte, error) {
	return candidatejson.EncodeCandidate("dnd scene description list", value)
}

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

// DecodeCandidate reads one strict durable JSON value before typed validators
// have approved it.
func (c *Codec) DecodeCandidate(content []byte) (dnd.SceneDescriptionList, error) {
	return candidatejson.DecodeCandidate[dnd.SceneDescriptionList]("dnd scene description list", content)
}

func validate(value dnd.SceneDescriptionList) error {
	if value.Scenes == nil {
		return fmt.Errorf("scenes must be present")
	}
	if len(value.Scenes) == 0 {
		return fmt.Errorf("scenes must not be empty")
	}
	for index, scene := range value.Scenes {
		prefix := fmt.Sprintf("scenes[%d]", index)
		if strings.TrimSpace(scene.ID) == "" {
			return fmt.Errorf("%s.id must not be empty", prefix)
		}
		if !validSceneKind(scene.Kind) {
			return fmt.Errorf("%s.kind must be supported", prefix)
		}
		if strings.TrimSpace(scene.Title) == "" {
			return fmt.Errorf("%s.title must not be empty", prefix)
		}
		if strings.TrimSpace(scene.Summary) == "" {
			return fmt.Errorf("%s.summary must not be empty", prefix)
		}
		if strings.TrimSpace(scene.SourceRef.SourceID) == "" {
			return fmt.Errorf("%s.source_ref.source_id must not be empty", prefix)
		}
		if err := sourcerange.Validate(scene.SourceRef); err != nil {
			return fmt.Errorf("%s.source_ref: %w", prefix, err)
		}
	}
	return nil
}

func validSceneKind(value dnd.SceneKind) bool {
	switch value {
	case dnd.SceneKindCombat, dnd.SceneKindNarrative, dnd.SceneKindRecap, dnd.SceneKindMeta:
		return true
	default:
		return false
	}
}
