// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package services

import (
	"context"
	"strings"
	"time"

	"wa-assistant/backend/database"
	"wa-assistant/backend/models"
)

// Compare against the database, not the retrieval cache. A turn may already
// have an approved answer when an operator removes or replaces its sources.
func currentKnowledgeSources(ctx context.Context, agentID uint, snapshots []models.Knowledge) ([]models.Knowledge, string) {
	if len(snapshots) == 0 {
		return nil, ""
	}
	unavailable := func(issue string) ([]models.Knowledge, string) { InvalidateKB(agentID); return nil, issue }
	if database.DB == nil {
		return unavailable("source_unavailable")
	}
	ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
	defer cancel()
	var current []models.Knowledge
	if err := database.DB.WithContext(ctx).Omit("embedding").Where("agent_id = ? AND id IN ? AND active = ? AND review_status = ?", agentID, knowledgeIDs(snapshots), true, "published").Find(&current).Error; err != nil {
		return unavailable("source_unavailable")
	}
	byID := make(map[uint]models.Knowledge, len(current))
	if err := ResolveKnowledgeSubjects(database.DB.WithContext(ctx), agentID, current); err != nil {
		return unavailable("source_unavailable")
	}
	for _, k := range current {
		byID[k.ID] = k
	}
	out, now := make([]models.Knowledge, 0, len(snapshots)), time.Now()
	for _, snapshot := range snapshots {
		k, ok := byID[snapshot.ID]
		if !ok || (k.EffectiveFrom != nil && k.EffectiveFrom.After(now)) || (k.EffectiveUntil != nil && !k.EffectiveUntil.After(now)) {
			return unavailable("source_unavailable")
		}
		if !k.UpdatedAt.Equal(snapshot.UpdatedAt) || k.Question != snapshot.Question || k.Scope != snapshot.Scope || k.SourceURL != snapshot.SourceURL || k.SubjectURL != snapshot.SubjectURL || k.SupersedesID != snapshot.SupersedesID || k.ImagePath != snapshot.ImagePath || !strings.HasPrefix(k.Answer, snapshot.Answer) {
			return unavailable("source_changed")
		}
		// Only the excerpt read by the model can support its answer.
		k.CharCount = len([]rune(k.Answer))
		k.Answer = snapshot.Answer
		out = append(out, k)
	}
	return out, ""
}

// KnowledgeIssue must also run after a typing delay, immediately before send.
// Already delivered WhatsApp messages cannot be recalled by deleting a fact.
func (r ChatResult) KnowledgeIssue(ctx context.Context, agentID uint) string {
	if r.Escalate && !r.HasVerifiedHandoffAnswer() {
		return ""
	}
	_, issue := currentKnowledgeSources(ctx, agentID, r.knowledgeSnapshot)
	if issue == "" {
		ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
		defer cancel()
		state := agentTurnState{productFacts: r.productSnapshot, orderFacts: r.orderSnapshot}
		issue = state.freshBusinessFacts(ctx, agentID)
	}
	if issue == "" {
		issue = customerMediaIssue(ctx, agentID, r.customerMediaSnapshot)
	}
	if issue == "" {
		issue = r.imageSnapshot.currentIssue(ctx, agentID)
	}
	return issue
}

// EnforceCurrentKnowledge is shared by the WhatsApp path and simulation.
func (r *ChatResult) EnforceCurrentKnowledge(ctx context.Context, agentID uint) {
	if issue := r.KnowledgeIssue(ctx, agentID); issue != "" {
		r.Escalate, r.HandoffReason, r.Reply = true, issue, ""
		r.handoffAnswer = ""
		r.AttachmentPath, r.AttachmentMime, r.AttachmentType, r.AttachmentSrc, r.AttachmentID = "", "", "", "", 0
		r.imageSnapshot = nil
		r.Trace.AnswerCheckIssue, r.Trace.ResponseValidated = issue, false
	}
}
