package services

import (
	"context"
	"fmt"
	"os"
	"strings"
	"testing"
	"time"

	"wa-assistant/backend/models"
)

// Read the configured provider, then evaluate only synthetic shop conversations.
func TestLiveDeepSeekContextualHandoff(t *testing.T) {
	if os.Getenv("CHATLOOP_RUN_LIVE_DEEPSEEK") != "1" {
		t.Skip("opt-in contextual handoff acceptance using isolated shop fixtures")
	}
	p, _, _, _ := liveDeepSeekAssistantSnapshot(t)
	db := agenticTestDB(t)
	if err := db.AutoMigrate(&models.AppSetting{}, &models.Agent{}, &models.Product{}); err != nil {
		t.Fatal(err)
	}
	if err := db.Create(&models.AppSetting{Key: "ai_provider", Value: "deepseek"}).Error; err != nil {
		t.Fatal(err)
	}
	agent := models.Agent{ID: 1, AgenticEnabled: true, ResponseLength: "short"}
	if err := db.Create(&models.Knowledge{AgentID: 1, Question: "Apa yang ditawarkan?", Answer: "Toko menawarkan Tas Nusa.", Active: true, ReviewStatus: "published", Scope: "general"}).Error; err != nil {
		t.Fatal(err)
	}
	t.Logf("model=%s; isolated fixtures, no WhatsApp or real queue", p.Model)
	for _, tc := range []struct {
		name, message, topic string
		history              []models.ChatHistory
	}{
		{"purchase", "Bisa beli Tas Nusa lewat chat ini?", "chat", nil},
		{"shipping_context", "Kalau ke sana berapa ongkirnya?", "bandung", []models.ChatHistory{{Message: "Saya mau kirim Tas Nusa ke Bandung.", Reply: "Informasi pengiriman apa yang ingin diketahui?"}}},
		{"discount", "Kalau beli dua Tas Nusa boleh dapat diskon?", "diskon", nil},
	} {
		t.Run(tc.name, func(t *testing.T) {
			result, err := chatAgentic(agent, "Asisten toko yang ramah dan jujur. Ikuti pengetahuan resmi.", "ramah", tc.message, tc.history, ChatOptions{Context: context.Background(), DryRun: true})
			t.Logf("handoff=%t notice=%q", result.Escalate, result.HandoffMessage())
			if err != nil || !result.Escalate || result.handoffReply == "" || !strings.Contains(strings.ToLower(result.HandoffMessage()), tc.topic) {
				t.Fatalf("contextual handoff failed: reason=%s err=%v", result.HandoffReason, err)
			}
		})
	}
}

// Real saved persona, published knowledge, model and embedding configuration;
// all execution is isolated in SQLite and never contacts WhatsApp customers.
func TestLiveDeepSeekHandoffRecovery(t *testing.T) {
	if os.Getenv("CHATLOOP_RUN_LIVE_DEEPSEEK") != "1" {
		t.Skip("opt-in paid DeepSeek acceptance with the configured knowledge")
	}
	p, agent, knowledge, products := liveDeepSeekAssistantSnapshot(t)
	db := agenticTestDB(t)
	if err := db.AutoMigrate(&models.AppSetting{}, &models.Agent{}, &models.Product{}); err != nil {
		t.Fatal(err)
	}
	if err := db.Create(&agent).Error; err != nil {
		t.Fatal(err)
	}
	if len(knowledge) > 0 {
		if err := db.Create(&knowledge).Error; err != nil {
			t.Fatal(err)
		}
	}
	if len(products) > 0 {
		if err := db.Create(&products).Error; err != nil {
			t.Fatal(err)
		}
	}
	for _, setting := range []models.AppSetting{{Key: "ai_provider", Value: "deepseek"}, {Key: "embedding_model", Value: os.Getenv("CHATLOOP_LIVE_EMBEDDING_MODEL")}} {
		if err := db.Create(&setting).Error; err != nil {
			t.Fatal(err)
		}
	}
	embMu.Lock()
	oldClient, oldModel, oldDims, oldEnabled := embClient, embModel, embDims, embEnabled
	embMu.Unlock()
	t.Cleanup(func() {
		embMu.Lock()
		embClient, embModel, embDims, embEnabled = oldClient, oldModel, oldDims, oldEnabled
		embMu.Unlock()
	})
	InitEmbedding()
	InvalidateKB(agent.ID)
	logDir := os.Getenv("CHATLOOP_AI_TEST_LOG_DIR")
	if logDir == "" {
		logDir = t.TempDir()
	}
	store := NewSimulationLogStore(logDir)
	t.Logf("model=%s published_sources=%d products=%d embedding_configured=%t", p.Model, len(knowledge), len(products), EmbeddingEnabled())
	greetingHistory := []models.ChatHistory{{Message: "hallo", Reply: "Halo kak, selamat datang di NgertiKode.id! Ada yang bisa saya bantu hari ini? 😊"}}
	type acceptanceCase struct {
		name, question   string
		history          []models.ChatHistory
		handoff, sources bool
	}
	cases := []acceptanceCase{
		{name: "greeting_haii", question: "haii"},
		{name: "greeting_halooo", question: "halooo kak"},
	}
	userLogHistory := []models.ChatHistory{{Message: "hai", Reply: "Halo kak! Ada yang bisa saya bantu terkait kursus atau source code dari NgertiKode.id? 😊"}}
	for round := 1; round <= 2; round++ {
		cases = append(cases,
			acceptanceCase{fmt.Sprintf("offer_%d", round), "jual apa", greetingHistory, false, true},
			acceptanceCase{fmt.Sprintf("casual_offer_%d", round), "oh, jual apa ?", greetingHistory, false, true},
			acceptanceCase{fmt.Sprintf("fresh_offer_%d", round), "anda jual apa", nil, false, true},
			acceptanceCase{fmt.Sprintf("user_log_offer_%d", round), "jual apa", userLogHistory, false, true},
		)
	}
	cases = append(cases,
		acceptanceCase{"source_link", "link kelasnya mana?", []models.ChatHistory{{Message: "kelas Laravel 12 itu apa?", Reply: "Masterclass Laravel 12 adalah kelas pemrograman web."}}, false, true},
		acceptanceCase{"human_request", "Saya mau bicara dengan CS manusia.", nil, true, false},
		acceptanceCase{"missing_fact", "Ada kursus merakit pesawat terbang? Kalau belum ada informasinya, teruskan ke CS ya.", nil, true, false},
	)
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			a := agent
			a.ResponseLength = "short"
			id := NewSimulationID()
			r, err := store.Start(a.ID, id, NewSimulationID(), map[string]any{"question": tc.question, "history": tc.history, "response_mode": a.ResponseLength})
			if err != nil {
				t.Fatal(err)
			}
			start := time.Now()
			result, callErr := chatAgentic(a, a.SystemPrompt, a.Tone, tc.question, tc.history, ChatOptions{Context: r.Context(context.Background()), DryRun: true})
			status := "completed"
			if result.Escalate {
				status = "handoff"
			}
			if callErr != nil {
				status = "error"
			}
			r.Finish(status, map[string]any{"reply": result.Reply, "provider": result.Trace.Provider, "model": result.Model, "handoff_reason": result.HandoffReason, "answer_check_issue": result.Trace.AnswerCheckIssue, "answer_sources": result.Trace.AnswerSources, "tool_names": result.Trace.ToolNames, "response_validated": result.Trace.ResponseValidated})
			t.Logf("turn=%s elapsed=%s status=%s tools=%s sources=%s chars=%d/%d issue=%s reply=%s", id, time.Since(start).Round(time.Millisecond), status, result.Trace.ToolNames, result.Trace.KnowledgeIDs, len([]rune(result.Reply)), result.Trace.ResponseMaxChars, result.Trace.AnswerCheckIssue, result.Reply)
			if callErr != nil {
				t.Fatalf("agent failed: %v", callErr)
			}
			if result.Escalate != tc.handoff {
				t.Fatalf("unexpected handoff=%t reason=%s", result.Escalate, result.HandoffReason)
			}
			if !tc.handoff && (!result.Trace.ResponseValidated || !strings.Contains(result.Trace.ToolNames, "check_answer") || len([]rune(result.Reply)) > result.Trace.ResponseMaxChars) {
				t.Fatal("reply is unvalidated or outside the saved style")
			}
			if tc.sources && (len(result.Trace.AnswerSources) == 0 || !strings.Contains(result.Trace.ToolNames, "search_knowledge")) {
				t.Fatal("business reply has no selected published source")
			}
			lower := strings.ToLower(result.Reply)
			course := strings.Contains(lower, "laravel") || strings.Contains(lower, "kursus") || strings.Contains(lower, "course") || strings.Contains(lower, "masterclass") || strings.Contains(lower, "pemrograman")
			code := strings.Contains(lower, "blast") || strings.Contains(lower, "source code")
			if strings.Contains(tc.name, "offer") && (!course || !code) {
				t.Fatal("known product categories were omitted")
			}
			if tc.name == "source_link" && !strings.Contains(result.Reply, "https://ngertikode.id/p/masterclass-laravel-12") {
				t.Fatal("requested source link is missing")
			}
		})
	}
}
