// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package handlers

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

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

// Simulation state lives in the test browser, never in customer sessions or
// submissions. Every turn rechecks the service against the authenticated agent.
type aiFormSimulation struct {
	FormID    uint              `json:"form_id"`
	ProductID uint              `json:"product_id,omitempty"`
	Data      map[string]string `json:"data"`
	StepIndex int               `json:"step_index"`
	Status    string            `json:"status"`
}

func simulateAIForm(ctx context.Context, agent models.Agent, state *aiFormSimulation, message string, initial bool, histories ...[]models.ChatHistory) (aiFormRuntimeResult, *aiFormSimulation) {
	if state == nil {
		return aiFormRuntimeResult{}, nil
	}
	var form models.AIForm
	var product models.Product
	if state.ProductID > 0 {
		if state.FormID != 0 || database.DB.Where("id = ? AND agent_id = ?", state.ProductID, agent.ID).First(&product).Error != nil || !productHasCheckout(product) {
			return aiFormRuntimeResult{handled: true, reply: "Produk ini tidak tersedia. Mulai ulang simulasi untuk mencoba produk lain."}, nil
		}
		form = productConversationForm(product)
	} else if database.DB.Where("id = ? AND agent_id = ? AND enabled = ?", state.FormID, agent.ID, true).First(&form).Error != nil {
		return aiFormRuntimeResult{handled: true, reply: "Layanan ini tidak tersedia. Mulai ulang simulasi untuk mencoba layanan lain."}, nil
	}
	steps := parseAIFormSteps(form)
	validate := func(step aiFormStepConfig, value string) (string, bool) {
		if state.ProductID > 0 {
			return checkoutAnswerValue(checkoutStepConfig{Key: step.Key, Label: step.Label, Type: step.Type, Required: step.Required, Options: step.Options}, value, "", 0)
		}
		return aiFormAnswerValue(step, value, "", 0)
	}
	data := map[string]string{}
	for _, step := range steps {
		if value, valid := validate(step, state.Data[step.Key]); valid && value != "" {
			data[step.Key] = value
			if state.Data["_incomplete_"+step.Key] == "true" {
				data["_incomplete_"+step.Key] = "true"
			}
		}
	}
	if target := state.Data[conversationEditKey]; target != "" {
		if target == "*" {
			data[conversationEditKey] = target
		}
		for _, step := range steps {
			if target == step.Key {
				data[conversationEditKey] = target
			}
		}
	}
	state.Data = data
	normalized := strings.ToLower(strings.TrimSpace(message))
	if normalized == "batal" {
		return aiFormRuntimeResult{handled: true, reply: "Pengisian dibatalkan. Tidak ada permintaan yang dicatat."}, nil
	}
	missing := nextMissingAIFormField(steps, data)
	if state.Status == "confirming" && missing == len(steps) && isAIFormConfirmationMessage(message) {
		return aiFormRuntimeResult{handled: true, reply: "Simulasi: data layanan sudah lengkap dan dikonfirmasi. Tidak ada permintaan sungguhan yang dibuat.", handoff: form.Handoff}, nil
	}
	if normalized == "ubah data" {
		state.Status = "collecting"
		state.StepIndex = len(steps)
		data[conversationEditKey] = "*"
		encoded, _ := json.Marshal(data)
		result := aiFormConversationResult(models.AIFormSession{DataJSON: string(encoded), Status: state.Status, StepIndex: state.StepIndex}, form, steps, false)
		return result, state
	}
	if state.StepIndex < 0 || state.StepIndex >= len(steps) {
		state.StepIndex = missing
	}
	expected := ""
	if !initial && state.Status == "collecting" && state.StepIndex < len(steps) {
		expected = steps[state.StepIndex].Key
	}
	history := []models.ChatHistory{}
	if len(histories) > 0 {
		history = histories[0]
	}
	extraction, err := extractAIFormFields(ctx, agent.ID, form.Name, steps, data, expected, message, services.ServiceConversationFromHistory(history, initial))
	if err != nil {
		return aiFormRuntimeResult{handled: true, reply: humanFacingHoldReply, handoff: true}, state
	}
	updated := map[string]bool{}
	for _, step := range steps {
		if proposal, ok := extraction.Fields[step.Key]; ok {
			if value, valid := validate(step, proposal.Value); valid {
				data[step.Key] = value
				updated[step.Key] = true
				setConversationFieldCompleteness(data, step.Key, extraction)
			}
		}
	}
	if extraction.Handoff {
		return aiFormRuntimeResult{handled: true, reply: humanFacingHoldReply, handoff: true}, state
	}
	markIncompleteConversationFields(steps, data, extraction)
	state.StepIndex = nextAIFormConversationField(steps, data, extraction.NextField)
	editIndex, editing := conversationEditField(steps, data, extraction, updated)
	if editing {
		state.StepIndex = editIndex
	}
	state.Status = "collecting"
	if !editing && state.StepIndex == len(steps) && extraction.Question == "" && !extraction.Pause {
		state.Status = "confirming"
	}
	encoded, _ := json.Marshal(data)
	session := models.AIFormSession{DataJSON: string(encoded), StepIndex: state.StepIndex, Status: state.Status}
	if state.Status == "confirming" && extraction.Question == "" && !extraction.Pause {
		return aiFormConfirmation(session, form, steps, true), state
	}
	return aiFormConversationResult(session, form, steps, extraction.Pause || extraction.Question != ""), state
}
