// Package identity implements deterministic session-scoped location identity.
package identity

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

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

const (
	// IdentityPolicy identifies the durable location ID derivation policy.
	IdentityPolicy = "dnd.location_registry.identity.v1"
	// Policy is an alias for IdentityPolicy.
	Policy = IdentityPolicy

	idPrefix = "location:sha256:"
)

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

const (
	IssueEmptyCanonicalName IssueCode = "empty_canonical_name"
	IssueMissingEvidence    IssueCode = "missing_evidence"
	IssueInvalidID          IssueCode = "invalid_id"
	IssueIDMismatch         IssueCode = "id_mismatch"
	IssueDuplicateID        IssueCode = "duplicate_id"
)

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

func (i Issue) Error() string { return string(i.Code) }

// NormalizeDisplay returns the durable display form without changing spelling
// or punctuation.
func NormalizeDisplay(value string) string {
	return strings.Join(strings.Fields(value), " ")
}

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

// DeriveID derives a location ID from name and the earliest canonical evidence
// reference. It returns an empty string when either identity component is not
// available, leaving validation to report the problem instead of manufacturing
// an ID.
func DeriveID(name string, refs []source.SourceRef) string {
	anchor, ok := earliestReference(refs)
	return deriveIDFromAnchor(name, anchor, ok)
}

func deriveIDFromAnchor(name string, anchor source.SourceRef, hasAnchor bool) string {
	comparisonName := ComparisonKey(name)
	if comparisonName == "" || !hasAnchor {
		return ""
	}

	input, err := json.Marshal([]any{
		IdentityPolicy,
		comparisonName,
		anchor.SourceID,
		anchor.StartUnitID,
		anchor.EndUnitID,
	})
	if err != nil {
		return ""
	}
	digest := sha256.Sum256(input)
	return idPrefix + hex.EncodeToString(digest[:])
}

// IDFor is an alias for DeriveID.
func IDFor(name string, refs []source.SourceRef) string { return DeriveID(name, refs) }

// IsValidID reports whether value has the exact durable location 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) }

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

// ValidateRegistry validates location IDs without modifying records or their
// source references. Equal comparison names are allowed because their evidence
// anchors are part of the identity policy.
func ValidateRegistry(locations []dnd.Location) []Issue {
	issues := make([]Issue, 0)
	idOwners := make(map[string][]int)

	for recordIndex, location := range locations {
		if ComparisonKey(location.Name) == "" {
			issues = append(issues, Issue{Code: IssueEmptyCanonicalName, RecordIndex: recordIndex, Value: location.Name})
		}
		anchor, hasAnchor := earliestReference(location.SourceRefs)
		if !hasAnchor {
			issues = append(issues, Issue{Code: IssueMissingEvidence, RecordIndex: recordIndex})
		}

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

	for recordIndex, location := range locations {
		if location.ID != "" && len(idOwners[location.ID]) > 1 && idOwners[location.ID][0] != recordIndex {
			issues = append(issues, Issue{Code: IssueDuplicateID, RecordIndex: recordIndex, Value: location.ID})
		}
	}

	return issues
}

func earliestReference(refs []source.SourceRef) (source.SourceRef, bool) {
	var earliest source.SourceRef
	found := false
	for _, ref := range refs {
		if !validIdentityReference(ref) {
			continue
		}
		if !found || referenceLess(ref, earliest) {
			earliest = ref
			found = true
		}
	}
	return earliest, found
}

func referenceLess(left, right source.SourceRef) bool {
	if left.SourceID != right.SourceID {
		return left.SourceID < right.SourceID
	}
	if left.StartUnitID != right.StartUnitID {
		return left.StartUnitID < right.StartUnitID
	}
	return left.EndUnitID < right.EndUnitID
}

func validIdentityReference(ref source.SourceRef) bool {
	return strings.TrimSpace(ref.SourceID) == ref.SourceID && ref.SourceID != "" && ref.StartUnitID > 0 && ref.EndUnitID > 0 && ref.StartUnitID <= ref.EndUnitID
}
