// Package registry resolves normalized item artifacts into immutable grounding
// data for future D&D consumers.
package registry

import (
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"

	"gitea.maximumdirect.net/eric/notarius/internal/core/source"
	"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
	itemcodec "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/itemregistry"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/items/identity"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared/diagnostics"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared/registryresolver"
)

const (
	ReferenceSlot = "item_registry"
	MaxBytes      = 1048576
	emptyPrompt   = `{"items":[]}`
)

// Registry is an immutable, validated item registry prepared for grounding.
// All accessors return defensive copies.
type Registry struct {
	bound            bool
	list             dnd.ItemRegistry
	canonical        []byte
	digest           string
	projectionDigest string
	promptInput      contracts.LLMInputMaterial
	lookupByKey      map[string]int
	lookupByID       map[string]int
}

// Resolver selects and memoizes immutable item registry views.
type Resolver struct {
	resolver *registryresolver.Resolver[*Registry]
}

// NewResolver validates the optional construction-time item reference and
// prepares the operation-time registry cache.
func NewResolver(references contracts.ReferenceSet) (*Resolver, error) {
	resolver, err := registryresolver.New(registryResolverConfig(), references)
	if err != nil {
		return nil, err
	}
	return &Resolver{resolver: resolver}, nil
}

// Seeded returns the immutable construction-time registry.
func (r *Resolver) Seeded() *Registry {
	if r == nil {
		return nil
	}
	return r.resolver.Seeded()
}

// Resolve returns the generated operation-time registry when supplied,
// otherwise it returns the construction-time registry.
func (r *Resolver) Resolve(references contracts.ReferenceSet) (*Registry, error) {
	if r == nil || r.resolver == nil {
		return Resolve(references)
	}
	return r.resolver.Resolve(references)
}

// Resolve prepares the optional item registry reference. An absent slot uses
// the exact empty prompt input and has no durable registry identity.
func Resolve(references contracts.ReferenceSet) (*Registry, error) {
	item, present, err := registryresolver.ResolveOptionalSingleItem(references, itemReferenceSpec())
	if err != nil {
		return nil, err
	}
	if !present {
		return emptyRegistry(), nil
	}
	return loadRegistry(item.Content)
}

func registryResolverConfig() registryresolver.Config[*Registry] {
	return registryresolver.Config[*Registry]{
		Reference: itemReferenceSpec(),
		Absent: func() (*Registry, error) {
			return emptyRegistry(), nil
		},
		Load: loadRegistry,
		SemanticIdentity: func(registry *Registry) string {
			return registry.Digest()
		},
	}
}

func itemReferenceSpec() registryresolver.ReferenceSpec {
	return registryresolver.ReferenceSpec{SlotName: ReferenceSlot, AcceptedMediaType: itemcodec.MediaType, MaxBytes: MaxBytes}
}

func emptyRegistry() *Registry {
	content := []byte(emptyPrompt)
	projectionDigest := semanticDigest(content)
	return &Registry{
		list:             dnd.ItemRegistry{Items: []dnd.Item{}},
		canonical:        append([]byte(nil), content...),
		projectionDigest: projectionDigest,
		promptInput:      contracts.NewLLMInputMaterial(ReferenceSlot, itemcodec.MediaType, content, projectionDigest, ""),
		lookupByKey:      map[string]int{},
		lookupByID:       map[string]int{},
	}
}

func loadRegistry(referenceContent []byte) (*Registry, error) {
	codec := itemcodec.New()
	value, err := codec.Decode(referenceContent)
	if err != nil {
		return nil, fmt.Errorf("decode item registry: invalid approved item JSON")
	}
	if issues := identity.ValidateList(value); len(issues) > 0 {
		return nil, fmt.Errorf("%s", formatIdentityIssues(issues))
	}
	content, err := codec.Encode(value)
	if err != nil {
		return nil, fmt.Errorf("encode canonical item registry: approved item value could not be encoded")
	}

	list := cloneItemRegistry(value)
	lookupByKey := make(map[string]int, len(list.Items))
	lookupByID := make(map[string]int, len(list.Items))
	for index, item := range list.Items {
		lookupByKey[identity.ComparisonKey(item.Name)] = index
		lookupByID[item.ID] = index
	}
	projection, err := promptProjection(list)
	if err != nil {
		return nil, fmt.Errorf("encode item registry projection: %w", err)
	}
	projectionDigest := semanticDigest(projection)
	return &Registry{
		bound:            true,
		list:             list,
		canonical:        append([]byte(nil), content...),
		digest:           semanticDigest(content),
		projectionDigest: projectionDigest,
		promptInput:      contracts.NewLLMInputMaterial(ReferenceSlot, itemcodec.MediaType, projection, projectionDigest, ""),
		lookupByKey:      lookupByKey,
		lookupByID:       lookupByID,
	}, nil
}

// Bound reports whether an item reference was supplied and validated.
func (r *Registry) Bound() bool { return r != nil && r.bound }

// Items returns a defensive copy of the validated item records.
func (r *Registry) Items() []dnd.Item {
	if r == nil {
		return nil
	}
	return cloneItems(r.list.Items)
}

// List returns a defensive copy of the validated item registry.
func (r *Registry) List() dnd.ItemRegistry {
	if r == nil {
		return dnd.ItemRegistry{}
	}
	return cloneItemRegistry(r.list)
}

// CanonicalBytes returns a defensive copy of the canonical durable JSON.
func (r *Registry) CanonicalBytes() []byte {
	if r == nil {
		return nil
	}
	return append([]byte(nil), r.canonical...)
}

// Digest returns the semantic SHA-256 digest of the canonical JSON, or an
// empty string when the registry is unbound.
func (r *Registry) Digest() string {
	if r == nil {
		return ""
	}
	return r.digest
}

// ProjectionDigest returns the SHA-256 digest of the exact names-only prompt
// projection, including for an unbound or empty registry.
func (r *Registry) ProjectionDigest() string {
	if r == nil {
		return ""
	}
	return r.projectionDigest
}

// Count returns the number of validated item records.
func (r *Registry) Count() int {
	if r == nil {
		return 0
	}
	return len(r.list.Items)
}

// PromptInput returns the ordered names-only registry projection as a
// content-safe prompt input. Durable IDs, evidence, and provenance are omitted.
func (r *Registry) PromptInput() contracts.LLMInputMaterial {
	if r == nil {
		return contracts.LLMInputMaterial{}
	}
	return r.promptInput.Clone()
}

// Lookup returns the canonical item for an exact canonical-name match under
// the item identity comparison policy.
func (r *Registry) Lookup(value string) (dnd.Item, bool) {
	if r == nil {
		return dnd.Item{}, false
	}
	index, ok := r.lookupByKey[identity.ComparisonKey(value)]
	if !ok {
		return dnd.Item{}, false
	}
	return cloneItem(r.list.Items[index]), true
}

// LookupID returns the canonical item for an exact durable ID.
func (r *Registry) LookupID(value string) (dnd.Item, bool) {
	if r == nil {
		return dnd.Item{}, false
	}
	index, ok := r.lookupByID[value]
	if !ok {
		return dnd.Item{}, false
	}
	return cloneItem(r.list.Items[index]), true
}

func semanticDigest(content []byte) string {
	sum := sha256.Sum256(content)
	return "sha256:" + hex.EncodeToString(sum[:])
}

type projectedItem struct {
	Name string `json:"name"`
}

type projectedItemRegistry struct {
	Items []projectedItem `json:"items"`
}

func promptProjection(list dnd.ItemRegistry) ([]byte, error) {
	projection := projectedItemRegistry{Items: make([]projectedItem, len(list.Items))}
	for index, item := range list.Items {
		projection.Items[index] = projectedItem{Name: item.Name}
	}
	return json.Marshal(projection)
}

func formatIdentityIssues(issues []identity.Issue) string {
	parts := make([]string, len(issues))
	for index, issue := range issues {
		parts[index] = fmt.Sprintf("%s at record %d", issue.Code, issue.RecordIndex)
	}
	return diagnostics.Aggregate("validate item registry identity", parts)
}

func cloneItemRegistry(value dnd.ItemRegistry) dnd.ItemRegistry {
	return dnd.ItemRegistry{Items: cloneItems(value.Items)}
}

func cloneItems(values []dnd.Item) []dnd.Item {
	if values == nil {
		return nil
	}
	cloned := make([]dnd.Item, len(values))
	for index, value := range values {
		cloned[index] = cloneItem(value)
	}
	return cloned
}

func cloneItem(value dnd.Item) dnd.Item {
	value.SourceRefs = append([]source.SourceRef(nil), value.SourceRefs...)
	return value
}
