// Package registry resolves normalized location artifacts into immutable
// ID-grounding data for D&D extraction modules.
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"
	locationcodec "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/locationregistry"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/locations/identity"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared/diagnostics"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared/registryresolver"
)

const (
	ReferenceSlot        = "location_registry"
	MaxBytes             = 1048576
	emptyRegistryContent = `{"locations":[]}`
)

// Registry is an immutable, validated location registry prepared for prompt
// grounding. All accessors return defensive copies.
type Registry struct {
	bound          bool
	list           dnd.LocationRegistry
	canonical      []byte
	digest         string
	identityDigest string
	lookupByID     map[string]int
}

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

// NewResolver validates a materialized construction-time location reference.
// An empty slot is permitted because a generated reference is supplied only at
// operation time.
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 validated 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 the location_registry
// slot is present, 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 validates an optional location-registry reference. An absent reference
// uses the canonical empty projection and has no durable registry identity.
func Resolve(references contracts.ReferenceSet) (*Registry, error) {
	item, present, err := registryresolver.ResolveOptionalSingleItem(references, locationReferenceSpec())
	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: locationReferenceSpec(),
		Absent: func() (*Registry, error) {
			return emptyRegistry(), nil
		},
		Load: loadRegistry,
		SemanticIdentity: func(registry *Registry) string {
			return registry.Digest()
		},
	}
}

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

func emptyRegistry() *Registry {
	content := []byte(emptyRegistryContent)
	identityDigest := semanticDigest(content)
	return &Registry{
		list:           dnd.LocationRegistry{Locations: []dnd.Location{}},
		canonical:      append([]byte(nil), content...),
		identityDigest: identityDigest,
		lookupByID:     map[string]int{},
	}
}

func loadRegistry(referenceContent []byte) (*Registry, error) {
	codec := locationcodec.New()
	value, err := codec.Decode(referenceContent)
	if err != nil {
		return nil, fmt.Errorf("decode location registry: invalid approved location 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 location registry: approved location value could not be encoded")
	}

	list := cloneLocationRegistry(value)
	lookupByID := make(map[string]int, len(list.Locations))
	for index, location := range list.Locations {
		lookupByID[location.ID] = index
	}
	projection, err := identityProjection(list)
	if err != nil {
		return nil, fmt.Errorf("encode location prompt projection: %w", err)
	}
	digest := semanticDigest(content)
	identityDigest := semanticDigest(projection)
	return &Registry{
		bound:          true,
		list:           list,
		canonical:      append([]byte(nil), content...),
		digest:         digest,
		identityDigest: identityDigest,
		lookupByID:     lookupByID,
	}, nil
}

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

// Locations returns a defensive copy of the validated location records.
func (r *Registry) Locations() []dnd.Location {
	if r == nil {
		return nil
	}
	return cloneLocations(r.list.Locations)
}

// List returns a defensive copy of the validated location registry.
func (r *Registry) List() dnd.LocationRegistry {
	if r == nil {
		return dnd.LocationRegistry{}
	}
	return cloneLocationRegistry(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 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
}

// IdentityDigest returns the digest of the ordered ID/name identity projection
// used by deterministic consumers.
func (r *Registry) IdentityDigest() string {
	if r == nil {
		return ""
	}
	return r.identityDigest
}

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

// Lookup returns the canonical location for an exact durable location ID.
func (r *Registry) Lookup(id string) (dnd.Location, bool) {
	if r == nil {
		return dnd.Location{}, false
	}
	index, ok := r.lookupByID[id]
	if !ok {
		return dnd.Location{}, false
	}
	return cloneLocation(r.list.Locations[index]), true
}

// Matches reports whether id resolves to exactly the supplied canonical name.
func (r *Registry) Matches(id, name string) bool {
	location, ok := r.Lookup(id)
	return ok && location.Name == name
}

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

type identityProjectedLocation struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

type identityProjectedLocationRegistry struct {
	Locations []identityProjectedLocation `json:"locations"`
}

func identityProjection(list dnd.LocationRegistry) ([]byte, error) {
	projection := identityProjectedLocationRegistry{Locations: make([]identityProjectedLocation, len(list.Locations))}
	for index, location := range list.Locations {
		projection.Locations[index] = identityProjectedLocation{ID: location.ID, Name: location.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 location registry identity", parts)
}

func cloneLocationRegistry(value dnd.LocationRegistry) dnd.LocationRegistry {
	return dnd.LocationRegistry{Locations: cloneLocations(value.Locations)}
}

func cloneLocations(values []dnd.Location) []dnd.Location {
	if values == nil {
		return nil
	}
	cloned := make([]dnd.Location, len(values))
	for index, value := range values {
		cloned[index] = cloneLocation(value)
	}
	return cloned
}

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