// Package itemoccurrences encodes durable D&D item-occurrence artifacts.
package itemoccurrences

import (
	"embed"
	"fmt"
	"strings"

	"gitea.maximumdirect.net/eric/notarius/internal/core/source"
	"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/itemoccurrences"
)

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

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

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

type Codec struct{}

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

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

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

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

// EncodeCandidate provides the durable representation before semantic
// validators have approved a value.
func (c *Codec) EncodeCandidate(value dnd.ItemOccurrenceList) ([]byte, error) {
	return candidatejson.EncodeCandidate("dnd item occurrence list", cloneList(value))
}

func (c *Codec) Decode(content []byte) (dnd.ItemOccurrenceList, error) {
	value, err := c.DecodeCandidate(content)
	if err != nil {
		return dnd.ItemOccurrenceList{}, err
	}
	if err := validate(value); err != nil {
		return dnd.ItemOccurrenceList{}, fmt.Errorf("decode dnd item occurrence list: %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.ItemOccurrenceList, error) {
	value, err := candidatejson.DecodeCandidate[dnd.ItemOccurrenceList]("dnd item occurrence list", content)
	if err != nil {
		return dnd.ItemOccurrenceList{}, err
	}
	return cloneList(value), nil
}

func validate(value dnd.ItemOccurrenceList) error {
	if value.Occurrences == nil {
		return fmt.Errorf("occurrences must be present")
	}
	for index, occurrence := range value.Occurrences {
		prefix := fmt.Sprintf("occurrences[%d]", index)
		if strings.TrimSpace(occurrence.ItemID) == "" {
			return fmt.Errorf("%s.item_id must not be empty", prefix)
		}
		if strings.TrimSpace(occurrence.Name) == "" {
			return fmt.Errorf("%s.name must not be empty", prefix)
		}
		if !itemoccurrences.SupportedKind(occurrence.Kind) {
			return fmt.Errorf("%s.kind must be supported", prefix)
		}
		if occurrence.From != "" && strings.TrimSpace(occurrence.From) == "" {
			return fmt.Errorf("%s.from must not be empty when present", prefix)
		}
		if occurrence.To != "" && strings.TrimSpace(occurrence.To) == "" {
			return fmt.Errorf("%s.to must not be empty when present", prefix)
		}
		if !itemoccurrences.ValidHolderCombination(occurrence.Kind, occurrence.From, occurrence.To) {
			return fmt.Errorf("%s holders are incompatible with %q", prefix, occurrence.Kind)
		}
		if occurrence.Quantity != nil && *occurrence.Quantity < 1 {
			return fmt.Errorf("%s.quantity must be positive when present", prefix)
		}
		if len(occurrence.SourceRefs) == 0 {
			return fmt.Errorf("%s.source_refs must contain at least one reference", prefix)
		}
		for refIndex, ref := range occurrence.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
}

func cloneList(value dnd.ItemOccurrenceList) dnd.ItemOccurrenceList {
	if value.Occurrences == nil {
		return dnd.ItemOccurrenceList{}
	}
	cloned := dnd.ItemOccurrenceList{Occurrences: make([]dnd.ItemOccurrence, len(value.Occurrences))}
	for index, occurrence := range value.Occurrences {
		cloned.Occurrences[index] = occurrence
		if occurrence.Quantity != nil {
			quantity := *occurrence.Quantity
			cloned.Occurrences[index].Quantity = &quantity
		}
		if occurrence.SourceRefs != nil {
			cloned.Occurrences[index].SourceRefs = append([]source.SourceRef(nil), occurrence.SourceRefs...)
		}
	}
	return cloned
}
