package combatturns

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

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

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

type Codec struct{}

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

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

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

func (c *Codec) Encode(value dnd.CombatTurnList) ([]byte, error) {
	if err := validate(value); err != nil {
		return nil, fmt.Errorf("encode dnd combat turn 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.CombatTurnList) ([]byte, error) {
	return candidatejson.EncodeCandidate("dnd combat turn list", value)
}

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

func validate(value dnd.CombatTurnList) error {
	if value.CombatTurns == nil {
		return fmt.Errorf("combat_turns must be present")
	}
	for index, turn := range value.CombatTurns {
		prefix := fmt.Sprintf("combat_turns[%d]", index)
		if strings.TrimSpace(turn.Actor) == "" {
			return fmt.Errorf("%s.actor must not be empty", prefix)
		}
		if !validTurnKind(turn.TurnKind) {
			return fmt.Errorf("%s.turn_kind must be supported", prefix)
		}
		if len(turn.SourceRefs) == 0 {
			return fmt.Errorf("%s.source_refs must contain at least one reference", prefix)
		}
		for refIndex, ref := range turn.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 validTurnKind(value dnd.CombatTurnKind) bool {
	switch value {
	case dnd.CombatTurnKindTurn, dnd.CombatTurnKindReaction, dnd.CombatTurnKindLegendaryAction, dnd.CombatTurnKindLairAction, dnd.CombatTurnKindOther:
		return true
	default:
		return false
	}
}
