package services

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

	"wa-assistant/backend/models"
)

// Paid opt-in tests borrow only the local provider configuration. All facts,
// history and assistant settings below are synthetic and stay in SQLite.
func TestLiveDeepSeekReplyPresentation(t *testing.T) {
	if os.Getenv("CHATLOOP_RUN_LIVE_DEEPSEEK") != "1" {
		t.Skip("opt-in paid DeepSeek reply presentation acceptance")
	}
	p, _, _, _ := liveDeepSeekAssistantSnapshot(t)
	db := agenticTestDB(t)
	if err := db.AutoMigrate(&models.AppSetting{}, &models.Agent{}, &models.Product{}); err != nil {
		t.Fatal(err)
	}
	agent := models.Agent{Name: "CS Toko Uji", AgenticEnabled: true, SystemPrompt: "Anda asisten virtual Toko Uji, membantu pelanggan memilih paket belajar. Semua fakta bisnis harus diperiksa pada sumber resmi.", Tone: "friendly"}
	if err := db.Create(&agent).Error; err != nil {
		t.Fatal(err)
	}
	source := models.Knowledge{
		AgentID: agent.ID, Active: true, ReviewStatus: "published", Scope: "general",
		Question: "Berapa harga Paket Basic dan Paket Pro, apa perbedaannya, dan bagaimana cara memesan?",
		Answer:   "Paket Basic berharga Rp190.000 sekali bayar, berisi video pembelajaran dan contoh kode. Paket Pro berharga Rp200.000 sekali bayar, berisi semua materi Basic serta sesi konsultasi melalui chat. Harga belum termasuk pajak. Pemesanan dilakukan berurutan: pilih paket, kirim nama dan email, lalu CS mengonfirmasi rincian pesanan.",
	}
	if err := db.Create(&source).Error; err != nil {
		t.Fatal(err)
	}
	if err := db.Create(&models.AppSetting{Key: "ai_provider", Value: "deepseek"}).Error; err != nil {
		t.Fatal(err)
	}
	InvalidateKB(agent.ID)
	defer InvalidateKB(agent.ID)
	logDir := os.Getenv("CHATLOOP_AI_TEST_LOG_DIR")
	if logDir == "" {
		logDir = t.TempDir()
	}
	store := NewSimulationLogStore(logDir)
	t.Logf("model=%s fixture_sources=1", p.Model)
	for _, tc := range []struct{ name, question, mode, layout string }{
		{"prices_short", "Berapa harga Paket Basic dan Paket Pro, apa perbedaannya?", "short", "prices"},
		{"prices_balanced", "Berapa harga Paket Basic dan Paket Pro, apa perbedaannya?", "balanced", "prices"},
		{"prices_detailed", "Berapa harga Paket Basic dan Paket Pro, apa perbedaannya?", "detailed", "prices"},
		{"one_price", "Berapa harga Paket Basic?", "short", "paragraph"},
		{"ordered_steps", "Bagaimana cara memesan paket belajar?", "balanced", "steps"},
	} {
		t.Run(tc.name, func(t *testing.T) {
			agent.ResponseLength = tc.mode
			id := NewSimulationID()
			record, err := store.Start(agent.ID, id, NewSimulationID(), map[string]any{"question": tc.question, "response_mode": tc.mode, "fixture": "reply_presentation"})
			if err != nil {
				t.Fatal(err)
			}
			started := time.Now()
			result, callErr := chatAgentic(agent, agent.SystemPrompt, agent.Tone, tc.question, nil, ChatOptions{Context: record.Context(context.Background()), DryRun: true})
			status := "completed"
			if result.Escalate {
				status = "handoff"
			}
			if callErr != nil {
				status = "error"
			}
			record.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 mode=%s tools=%s chars=%d/%d reply=%s", id, time.Since(started).Round(time.Millisecond), status, result.Trace.ResponseMode, result.Trace.ToolNames, len([]rune(result.Reply)), result.Trace.ResponseMaxChars, result.Reply)
			if callErr != nil {
				t.Fatalf("agent failed: %v", callErr)
			}
			if result.Escalate || !result.Trace.ResponseValidated || !strings.Contains(result.Trace.ToolNames, "check_answer") || len(result.Trace.AnswerSources) != 1 {
				t.Fatalf("fixture answer was not grounded and approved: handoff=%s issue=%s", result.HandoffReason, result.Trace.AnswerCheckIssue)
			}
			if result.Trace.ResponseMode != tc.mode || len([]rune(result.Reply)) > result.Trace.ResponseMaxChars {
				t.Fatal("saved response style was not respected")
			}
			if strings.ContainsAny(result.Reply, "\u2014\u2013") {
				t.Error("long dash remains in customer prose")
			}
			plain := strings.NewReplacer("*", "", "_", "").Replace(strings.ToLower(result.Reply))
			if rupiahAmountPattern.MatchString(result.Reply) && !strings.Contains(plain, "belum termasuk pajak") {
				t.Error("price qualification from the fixture was omitted")
			}
			switch tc.layout {
			case "prices":
				if !hasRupiahPrice(result.Reply, 190000) || !hasRupiahPrice(result.Reply, 200000) {
					t.Error("requested price was omitted or changed")
				}
				if len(regexp.MustCompile(`(?m)^- .*\bRp`).FindAllString(result.Reply, -1)) < 2 {
					t.Error("parallel prices must be separate list items")
				}
			case "paragraph":
				if regexp.MustCompile(`(?m)^[-0-9][.) ]`).MatchString(result.Reply) || !hasRupiahPrice(result.Reply, 190000) || hasRupiahPrice(result.Reply, 200000) {
					t.Error("a single requested price should remain a focused paragraph")
				}
			case "steps":
				if !regexp.MustCompile(`(?m)^1\. `).MatchString(result.Reply) || !regexp.MustCompile(`(?m)^2\. `).MatchString(result.Reply) {
					t.Error("sequential instructions need numbered lines")
				}
			}
		})
	}
}
