// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package handlers

import (
	"context"
	"encoding/json"
	"strings"
	"time"

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

// Product and service collection share the same language understanding and
// conversational prompt. The adapter is never stored as a real AI form.
func productConversationForm(product models.Product) models.AIForm {
	steps := []aiFormStepConfig{}
	for _, step := range parseCheckoutSteps(product) {
		steps = append(steps, aiFormStepConfig{Key: step.Key, Label: step.Label, Type: step.Type, Required: step.Required, Options: step.Options})
	}
	raw, _ := json.Marshal(steps)
	return models.AIForm{AgentID: product.AgentID, Name: "Pesanan " + product.Name, StepsJSON: string(raw), Handoff: product.CheckoutHandoff}
}

func productConversationResult(session models.ProductCheckoutSession, product models.Product, pause bool) productInteractionResult {
	form := productConversationForm(product)
	result := aiFormConversationResult(models.AIFormSession{DataJSON: session.DataJSON, StepIndex: session.StepIndex, Status: session.Status}, form, parseAIFormSteps(form), pause)
	return productInteractionResult{aiContext: result.context}
}

func collectProductCheckoutConversation(session models.ProductCheckoutSession, product models.Product, message string, initial bool) productInteractionResult {
	form := productConversationForm(product)
	steps := parseAIFormSteps(form)
	data := map[string]string{}
	_ = json.Unmarshal([]byte(session.DataJSON), &data)
	public := map[string]string{}
	for _, step := range steps {
		if data[step.Key] != "" {
			public[step.Key] = data[step.Key]
		}
	}
	expected := ""
	if !initial && session.Status == "collecting" && session.StepIndex >= 0 && session.StepIndex < len(steps) {
		expected = steps[session.StepIndex].Key
	}
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	history, err := services.LoadRecentChatContext(ctx, database.DB, session.AgentID, session.Sender, nil)
	if err != nil {
		return productInteractionResult{handled: true, handoff: true, reply: humanFacingHoldReply}
	}
	extraction, err := extractAIFormFields(ctx, session.AgentID, form.Name, steps, public, expected, message, services.ServiceConversationFromHistory(history, initial))
	if err != nil {
		return productInteractionResult{handled: true, handoff: true, reply: humanFacingHoldReply}
	}
	return applyProductCheckoutExtraction(session, product, extraction)
}

func applyProductCheckoutExtraction(session models.ProductCheckoutSession, product models.Product, extraction services.ServiceExtraction) productInteractionResult {
	steps := parseCheckoutSteps(product)
	data := map[string]string{}
	_ = json.Unmarshal([]byte(session.DataJSON), &data)
	updated := map[string]bool{}
	for _, step := range steps {
		if proposal, ok := extraction.Fields[step.Key]; ok {
			if value, valid := checkoutAnswerValue(step, proposal.Value, "", session.ID); valid {
				data[step.Key], data["_source_"+step.Key] = value, proposal.Evidence
				updated[step.Key] = true
				setConversationFieldCompleteness(data, step.Key, extraction)
			}
		}
	}
	form := productConversationForm(product)
	markIncompleteConversationFields(parseAIFormSteps(form), data, extraction)
	session.StepIndex = nextAIFormConversationField(parseAIFormSteps(form), data, extraction.NextField)
	editIndex, editing := conversationEditField(parseAIFormSteps(form), data, extraction, updated)
	if editing {
		session.StepIndex = editIndex
	}
	session.Status = "collecting"
	if !editing && session.StepIndex == len(steps) && extraction.Question == "" && !extraction.Pause && !extraction.Handoff {
		session.Status = "confirming"
	}
	raw, _ := json.Marshal(data)
	session.DataJSON = string(raw)
	session.ExpiresAt = time.Now().Add(checkoutSessionTTL)
	if err := database.DB.Model(&session).Updates(map[string]any{"step_index": session.StepIndex, "status": session.Status, "data_json": session.DataJSON, "expires_at": session.ExpiresAt}).Error; err != nil {
		return productInteractionResult{handled: true, reply: "Data pesanan sementara belum berhasil dicatat. Boleh coba lagi sebentar?"}
	}
	if extraction.Handoff {
		if extraction.Question != "" {
			// Preserve the side question while requiring the final answer to
			// enter the CS queue. Collection cannot answer business facts itself.
			result := productConversationResult(session, product, true)
			result.requiredHandoff = true
			return result
		}
		return productInteractionResult{handled: true, handoff: true, reply: humanFacingHoldReply}
	}
	if session.Status == "confirming" {
		return checkoutConfirmation(session, product, steps, true)
	}
	return productConversationResult(session, product, extraction.Pause || extraction.Question != "")
}

func renderProductCheckoutConversation(ctx context.Context, agent models.Agent, result productInteractionResult, message string, history []models.ChatHistory, sender string) productInteractionResult {
	if result.aiContext == "" {
		return result
	}
	answer := renderAIFormConversation(ctx, agent, aiFormRuntimeResult{context: result.aiContext, requiredHandoff: result.requiredHandoff}, message, history, false, sender)
	result.handled, result.handoff, result.aiContext = true, answer.handoff, ""
	result.reply = answer.reply
	if result.handoff && strings.TrimSpace(result.reply) == "" {
		result.reply = humanFacingHoldReply
	}
	return result
}
