package spells

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.spells"
	SchemaName    = "notarius_dnd_spells_v1"
	SchemaVersion = "v1"
	MediaType     = "application/json"
)

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

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

type Codec struct{}

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

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

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

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

func (c *Codec) Metadata(value dnd.SpellList) map[string]any {
	return map[string]any{"spell_cast_count": len(value.SpellCasts)}
}

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

// EncodeCandidate provides the same stable representation before typed
// validators have approved a value.
func (c *Codec) EncodeCandidate(value dnd.SpellList) ([]byte, error) {
	return candidatejson.EncodeCandidate("dnd spell list", value)
}

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

// DecodeCandidate reads the durable representation before semantic validators
// have approved it.
func (c *Codec) DecodeCandidate(content []byte) (dnd.SpellList, error) {
	return candidatejson.DecodeCandidate[dnd.SpellList]("dnd spell list", content)
}

func validate(value dnd.SpellList) error {
	if value.SpellCasts == nil {
		return fmt.Errorf("spell_casts must be present")
	}
	for index, spell := range value.SpellCasts {
		if strings.TrimSpace(spell.Caster) == "" {
			return fmt.Errorf("spell_casts[%d].caster must not be empty", index)
		}
		if strings.TrimSpace(spell.Spell) == "" {
			return fmt.Errorf("spell_casts[%d].spell must not be empty", index)
		}
		if len(spell.SourceRefs) == 0 {
			return fmt.Errorf("spell_casts[%d].source_refs must not be empty", index)
		}
		for refIndex, ref := range spell.SourceRefs {
			if strings.TrimSpace(ref.SourceID) == "" {
				return fmt.Errorf("spell_casts[%d].source_refs[%d].source_id must not be empty", index, refIndex)
			}
			if err := sourcerange.Validate(ref); err != nil {
				return fmt.Errorf("spell_casts[%d].source_refs[%d]: %w", index, refIndex, err)
			}
		}
	}
	return nil
}
