package sourcerefs

import (
	"context"
	"fmt"

	"gitea.maximumdirect.net/eric/notarius/internal/core/source"
	"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
	"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared/diagnostics"
	npcshape "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/validate/npcregistry/shape"
)

const (
	Key        = "extract/dnd/npc-registry/source_refs"
	ReasonCode = "invalid_npc_source_refs"
	policy     = "dnd.npc_registry.validator.source_refs.v2"
)

type Options struct{}
type Validator struct{}

var _ contracts.TypedValidator[dnd.NPCRegistry] = (*Validator)(nil)
var _ pipeline.CheckpointFingerprintProvider = (*Validator)(nil)

func New(Options) *Validator      { return &Validator{} }
func (v *Validator) Name() string { return Key }
func (v *Validator) ExecutionClass() contracts.ExecutionClass {
	return contracts.ExecutionClassDeterministic
}
func (v *Validator) CheckpointFingerprints() []pipeline.CheckpointFingerprint {
	return []pipeline.CheckpointFingerprint{{Name: "policy", Value: policy}}
}

func (v *Validator) Validate(_ context.Context, req contracts.TypedValidationRequest[dnd.NPCRegistry]) (contracts.ValidationResult, error) {
	if req.Stage == string(pipeline.StageExtract) && req.Chunk == nil {
		return contracts.ValidationResult{}, fmt.Errorf("NPC source-reference validator requires the current extraction chunk")
	}
	if err := npcshape.Validate(req.Value); err != nil {
		return contracts.ValidationResult{Approved: true}, nil
	}
	index := source.NewDocumentIndex(req.Source)
	var coverage *chunkCoverage
	if req.Stage == string(pipeline.StageExtract) {
		coverage = newChunkCoverage(req.Chunk)
	}
	issues := make([]string, 0)
	for npcIndex, npc := range req.Value.NPCs {
		for refIndex, ref := range npc.SourceRefs {
			if err := index.ValidateRef(ref); err != nil {
				issues = append(issues, fmt.Sprintf("npcs[%d].source_refs[%d]: %s", npcIndex, refIndex, diagnostics.Truncate(err.Error())))
				continue
			}
			if coverage != nil && !coverage.contains(req.Source, ref) {
				issues = append(issues, fmt.Sprintf("npcs[%d].source_refs[%d]: source reference is outside the current extraction chunk", npcIndex, refIndex))
			}
		}
	}
	if len(issues) == 0 {
		return contracts.ValidationResult{Approved: true}, nil
	}
	return rejection(diagnostics.Aggregate("invalid NPC source references", issues)), nil
}

type chunkCoverage struct {
	sourceID string
	unitIDs  map[int]struct{}
}

func newChunkCoverage(chunk *source.Chunk) *chunkCoverage {
	coverage := &chunkCoverage{sourceID: chunk.SourceID, unitIDs: make(map[int]struct{}, len(chunk.Units))}
	for _, unit := range chunk.Units {
		coverage.unitIDs[unit.ID] = struct{}{}
	}
	return coverage
}

func (coverage *chunkCoverage) contains(doc *source.SourceDocument, ref source.SourceRef) bool {
	if coverage == nil || doc == nil || ref.SourceID != coverage.sourceID {
		return false
	}
	start, startOK := source.UnitIndex(doc, ref.StartUnitID)
	end, endOK := source.UnitIndex(doc, ref.EndUnitID)
	if !startOK || !endOK || start > end {
		return false
	}
	for position := start; position <= end; position++ {
		if _, found := coverage.unitIDs[doc.Units[position].ID]; !found {
			return false
		}
	}
	return true
}

func Spec() pipeline.ValidatorSpec {
	return pipeline.ValidatorSpec{Key: Key, ExecutionClass: contracts.ExecutionClassDeterministic}
}

func Register(registry *pipeline.ValidatorRegistry) error {
	return pipeline.RegisterTypedValidatorBuilder(registry, dnd.NPCRegistryKind, Spec(), validateOptions, func(request pipeline.BuildRequest) (contracts.TypedValidator[dnd.NPCRegistry], error) {
		options, err := DecodeOptions(request.Options)
		if err != nil {
			return nil, err
		}
		return New(options), nil
	})
}

func DecodeOptions(options map[string]any) (Options, error) {
	if err := pipeline.RejectUnknownOptions(options); err != nil {
		return Options{}, err
	}
	return Options{}, nil
}

func validateOptions(options map[string]any) error { _, err := DecodeOptions(options); return err }

func rejection(message string) contracts.ValidationResult {
	return contracts.ValidationResult{Approved: false, ReasonCode: ReasonCode, Message: message}
}
