// Package identity owns the stable identity policy for D&D item types.
package identity

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

	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared"
)

const (
	// Policy identifies the complete item comparison and ID derivation policy.
	// A future semantic change must use a new value.
	Policy = "dnd.item_registry.identity.v1"
	// IdentityPolicy is an explicit alias for callers recording policy
	// fingerprints.
	IdentityPolicy = Policy
)

const idPrefix = "item:sha256:"

// IssueCode identifies one deterministic registry identity problem.
type IssueCode string

const (
	IssueEmptyCanonicalName IssueCode = "empty_canonical_name"
	IssueInvalidID          IssueCode = "invalid_id"
	IssueIDMismatch         IssueCode = "id_mismatch"
	IssueDuplicateCanonical IssueCode = "duplicate_canonical_identity"
	IssueDuplicateID        IssueCode = "duplicate_id"
)

// Issue is an inspectable identity validation problem.
type Issue struct {
	Code        IssueCode
	RecordIndex int
	Value       string
}

// NormalizeDisplay trims and collapses Unicode whitespace while retaining all
// other observed spelling and punctuation.
func NormalizeDisplay(value string) string {
	return strings.Join(strings.Fields(value), " ")
}

// ComparisonKey returns the stable key used for item-type identity comparisons.
func ComparisonKey(value string) string {
	return shared.ComparisonKey(value)
}

// DeriveID returns the deterministic ID for an item type. Empty identity keys
// intentionally produce an empty ID so shape validation can report the missing
// identity instead of manufacturing one.
func DeriveID(name string) string {
	key := ComparisonKey(name)
	if key == "" {
		return ""
	}
	identity, err := json.Marshal([]string{Policy, key})
	if err != nil {
		return ""
	}
	digest := sha256.Sum256(identity)
	return idPrefix + hex.EncodeToString(digest[:])
}

// IDFor is a concise alias for DeriveID for callers that work with IDs as
// values rather than derivation operations.
func IDFor(name string) string { return DeriveID(name) }

// IsValidID reports whether value has the exact durable item ID syntax.
func IsValidID(value string) bool {
	if len(value) != len(idPrefix)+sha256.Size*2 || !strings.HasPrefix(value, idPrefix) {
		return false
	}
	for _, r := range value[len(idPrefix):] {
		if !(r >= '0' && r <= '9') && !(r >= 'a' && r <= 'f') {
			return false
		}
	}
	return true
}

// ValidID is an alias for IsValidID.
func ValidID(value string) bool { return IsValidID(value) }

// ValidateRegistry checks item-type identity invariants without changing the
// input. Items with the same comparison name describe the same item type and
// are rejected as duplicate registry records.
func ValidateRegistry(items []dnd.Item) []Issue {
	issues := make([]Issue, 0)
	canonicalOwners := make(map[string][]int)
	idOwners := make(map[string][]int)

	for recordIndex, item := range items {
		canonical := ComparisonKey(item.Name)
		if canonical == "" {
			issues = append(issues, Issue{Code: IssueEmptyCanonicalName, RecordIndex: recordIndex, Value: item.Name})
		} else {
			canonicalOwners[canonical] = append(canonicalOwners[canonical], recordIndex)
		}

		if !IsValidID(item.ID) {
			issues = append(issues, Issue{Code: IssueInvalidID, RecordIndex: recordIndex, Value: item.ID})
		} else if expected := DeriveID(item.Name); item.ID != expected {
			issues = append(issues, Issue{Code: IssueIDMismatch, RecordIndex: recordIndex, Value: item.ID})
		}
		if item.ID != "" {
			idOwners[item.ID] = append(idOwners[item.ID], recordIndex)
		}
	}

	for recordIndex, item := range items {
		canonical := ComparisonKey(item.Name)
		if canonical != "" && len(canonicalOwners[canonical]) > 1 && canonicalOwners[canonical][0] != recordIndex {
			issues = append(issues, Issue{Code: IssueDuplicateCanonical, RecordIndex: recordIndex, Value: item.Name})
		}
		if item.ID != "" && len(idOwners[item.ID]) > 1 && idOwners[item.ID][0] != recordIndex {
			issues = append(issues, Issue{Code: IssueDuplicateID, RecordIndex: recordIndex, Value: item.ID})
		}
	}

	return issues
}

// ValidateList validates the identity members of list.
func ValidateList(list dnd.ItemRegistry) []Issue { return ValidateRegistry(list.Items) }

// Error makes an issue useful in simple callers while preserving its
// structured fields for aggregate diagnostics.
func (i Issue) Error() string {
	return fmt.Sprintf("%s at record %d", i.Code, i.RecordIndex)
}
