// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package handlers

import (
	"crypto/sha256"
	"errors"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"

	"github.com/gin-gonic/gin"
	"wa-assistant/backend/models"
	"wa-assistant/backend/services"
)

var simulationLogs = services.NewSimulationLogStore(".tmp/ai-simulator")

func startSimulationLog(c *gin.Context, agent models.Agent, turnID, sessionID, message string, history []models.ChatHistory) (*services.SimulationRecorder, string, string, bool) {
	c.Set("ai_readiness_agentic", agent.AgenticEnabled)
	if fingerprint, err := services.AIReadinessFingerprint(c.Request.Context(), agent); err == nil {
		c.Set("ai_readiness_fingerprint", fingerprint)
		c.Set("ai_readiness_agent", agent.ID)
	}
	if turnID == "" {
		turnID = services.NewSimulationID()
	}
	if sessionID == "" {
		sessionID = services.NewSimulationID()
	}
	if !services.ValidSimulationID(turnID) || !services.ValidSimulationID(sessionID) {
		c.JSON(400, gin.H{"error": "ID pengujian tidak valid. Mulai ulang simulasi."})
		return nil, "", "", false
	}
	contextMessages := make([]map[string]string, 0, len(history)*2)
	for _, row := range history {
		if row.Message != "" {
			contextMessages = append(contextMessages, map[string]string{"role": "user", "text": row.Message})
		}
		if row.Reply != "" {
			contextMessages = append(contextMessages, map[string]string{"role": "bot", "text": row.Reply})
		}
	}
	recorder, err := simulationLogs.Start(agent.ID, turnID, sessionID, map[string]any{
		"question": message, "history_used": contextMessages, "user_id": currentUserID(c),
		"question_chars": len([]rune(message)), "history_message_count": len(contextMessages),
		"settings": map[string]any{"agentic_enabled": agent.AgenticEnabled, "ai_enabled": agent.AIEnabled, "response_length": agent.ResponseLength, "tone": agent.Tone, "persona_fingerprint": fmt.Sprintf("%x", sha256.Sum256([]byte(agent.SystemPrompt)))},
	})
	if errors.Is(err, os.ErrExist) {
		c.JSON(409, gin.H{"error": "ID pengujian ini sudah digunakan. Periksa log atau kirim pengujian baru.", "turn_id": turnID, "session_id": sessionID})
		return nil, "", "", false
	}
	if err != nil {
		log.Printf("[ai-simulator] turn=%s agent=%d log_unavailable", turnID, agent.ID)
	}
	c.Request = c.Request.WithContext(recorder.Context(c.Request.Context()))
	c.Header("X-AI-Test-ID", turnID)
	c.Header("Cache-Control", "no-store")
	return recorder, turnID, sessionID, true
}

func respondSimulation(c *gin.Context, recorder *services.SimulationRecorder, turnID, sessionID string, code int, body gin.H) {
	status := "completed"
	if body["escalate"] == true {
		status = "handoff"
	}
	if code >= 400 {
		status = "error"
	}
	// Keep only diagnostics, never signed media URLs or service session tokens.
	data := map[string]any{}
	for _, key := range []string{"reply", "error", "error_code", "provider", "model", "response_mode", "response_preference_source", "response_max_chars", "response_chars", "response_validated", "response_retried", "response_kind", "answer_check_issue", "answer_sources", "tool_names", "tool_calls", "handoff_reason", "knowledge_ids", "product_ids", "retrieval_mode", "latency_ms"} {
		if value, ok := body[key]; ok {
			data[key] = value
		}
	}
	body["turn_id"], body["session_id"] = turnID, sessionID
	body["log_saved"] = recorder.Finish(status, data)
	if code < 400 {
		sources, _ := body["answer_sources"].([]services.AnswerSource)
		answer := body["escalate"] != true && body["response_validated"] == true && body["response_kind"] == "answer" && len(sources) > 0
		if !c.GetBool("ai_readiness_agentic") {
			ids, _ := body["knowledge_ids"].(string)
			reply, _ := body["reply"].(string)
			answer = body["escalate"] != true && body["response_kind"] == "answer" && ids != "" && reply != ""
		}
		reason, _ := body["handoff_reason"].(string)
		handoff := body["escalate"] == true && (reason == "customer_request" || reason == "sensitive_issue" || reason == "insufficient_evidence")
		if err := services.RecordAISimulationProof(c.Request.Context(), c.GetUint("ai_readiness_agent"), c.GetString("ai_readiness_fingerprint"), answer, handoff); err != nil {
			log.Printf("[ai-simulator] readiness proof unavailable")
		}
	}
	log.Printf("[ai-simulator] turn=%s status=%s saved=%t", turnID, status, body["log_saved"])
	c.JSON(code, body)
}

// Same tenant/assignment authorization as the simulator; files are never served
// as static assets. A test ID alone cannot grant access to another assistant.
func GetSimulationLog(c *gin.Context) {
	id, ok := resolveAgent(c)
	if !ok {
		return
	}
	c.Header("Cache-Control", "no-store")
	result, err := simulationLogs.Read(id, c.Param("turnID"))
	if errors.Is(err, os.ErrNotExist) {
		c.JSON(404, gin.H{"error": "Log uji belum tersedia atau sudah kedaluwarsa."})
		return
	}
	if errors.Is(err, services.ErrSimulationID) {
		c.JSON(400, gin.H{"error": "ID pengujian tidak valid."})
		return
	}
	if err != nil {
		c.JSON(503, gin.H{"error": "Log pengujian belum dapat dibaca."})
		return
	}
	if c.Query("detail") != "1" {
		result = simulationProgress(result)
	}
	c.JSON(200, result)
}

func SaveSimulationFeedback(c *gin.Context) {
	id, ok := resolveAgent(c)
	if !ok {
		return
	}
	c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 16*1024)
	var req struct {
		Rating string `json:"rating"`
		Note   string `json:"note"`
	}
	if c.ShouldBindJSON(&req) != nil || len([]rune(req.Note)) > 2000 || (req.Rating == "needs_work" && strings.TrimSpace(req.Note) == "") {
		c.JSON(400, gin.H{"error": "Jelaskan bagian yang kurang tepat, maksimal 2.000 karakter."})
		return
	}
	err := simulationLogs.Feedback(id, c.Param("turnID"), req.Rating, req.Note, currentUserID(c))
	if errors.Is(err, os.ErrNotExist) {
		c.JSON(404, gin.H{"error": "Log uji tidak ditemukan atau sudah kedaluwarsa."})
		return
	}
	if errors.Is(err, services.ErrSimulationFeedback) || errors.Is(err, services.ErrSimulationID) {
		c.JSON(400, gin.H{"error": "Penilaian belum bisa disimpan untuk pengujian ini."})
		return
	}
	if err != nil {
		c.JSON(503, gin.H{"error": "Penilaian belum tersimpan. Coba lagi."})
		return
	}
	c.JSON(200, gin.H{"saved": true})
}
