package services

import (
	"context"
	"fmt"
	"strings"
	"testing"

	"github.com/cloudwego/eino/components/tool"
	"wa-assistant/backend/models"
)

// Regression fixtures use isolated SQLite without a provider or WhatsApp.
func TestAgentGroundingRegressionFinalGuardRevalidatesOperationalFacts(t *testing.T) {
	t.Run("product_price", func(t *testing.T) {
		db := agenticTestDB(t)
		if err := db.AutoMigrate(&models.Product{}); err != nil {
			t.Fatal(err)
		}
		p := models.Product{AgentID: 1, TenantID: 1, Name: "Kaos Nusa", Price: "Rp75.000"}
		if err := db.Create(&p).Error; err != nil {
			t.Fatal(err)
		}
		s := &agentTurnState{productFacts: map[uint]models.Product{p.ID: p}}
		if issue := s.freshBusinessFacts(context.Background(), 1); issue != "" {
			t.Fatal(issue)
		}
		// Preserve the reviewed evidence through the same response construction as chatAgentic.
		r := createChatResult(1, "Harga Kaos Nusa Rp75.000.", "fixture", false, nil, joinUintIDs([]uint{p.ID}), "Harga kaos?", nil, RetrievalTrace{RetrievalMode: "agentic", ResponseValidated: true})
		s.attachDeliveryEvidence(&r)
		if err := db.Model(&p).UpdateColumn("price", "Rp99.000").Error; err != nil {
			t.Fatal(err)
		}
		if issue := s.freshBusinessFacts(context.Background(), 1); issue != "operational_changed" {
			t.Fatalf("fixture did not change fact: %q", issue)
		}
		if issue := r.KnowledgeIssue(context.Background(), 1); issue == "" {
			t.Error("BUG: final send guard accepts obsolete Rp75.000 after price became Rp99.000")
		}
	})
	t.Run("order_status", func(t *testing.T) {
		db := agenticTestDB(t)
		o := models.ProductOrder{AgentID: 1, Sender: "customer-a", OrderCode: "AUDIT-1", Status: "pending"}
		if err := db.Create(&o).Error; err != nil {
			t.Fatal(err)
		}
		s := &agentTurnState{orderFacts: map[uint]models.ProductOrder{o.ID: o}}
		if issue := s.freshBusinessFacts(context.Background(), 1); issue != "" {
			t.Fatal(issue)
		}
		r := createChatResult(1, "Pesanan Kakak masih menunggu pembayaran.", "fixture", false, nil, "", "Status pesanan?", nil, RetrievalTrace{RetrievalMode: "agentic", ResponseValidated: true})
		s.attachDeliveryEvidence(&r)
		if err := db.Model(&o).UpdateColumn("status", "paid").Error; err != nil {
			t.Fatal(err)
		}
		if issue := s.freshBusinessFacts(context.Background(), 1); issue != "operational_changed" {
			t.Fatalf("fixture did not change fact: %q", issue)
		}
		if issue := r.KnowledgeIssue(context.Background(), 1); issue == "" {
			t.Error("BUG: final send guard accepts obsolete pending status after order became paid")
		}
	})
}

func TestAgentGroundingRegressionManualKBComparisonIncludesOpposingRule(t *testing.T) {
	db := agenticTestDB(t)
	a := models.Knowledge{AgentID: 1, Question: "Apakah Paket Nusa boleh dijual ulang?", Answer: "Paket Nusa boleh dijual ulang.", Scope: "general", Active: true, ReviewStatus: "published"}
	b := models.Knowledge{AgentID: 1, Question: "Batasan lisensi Paket Nusa?", Answer: "Paket Nusa tidak boleh dijual ulang.", Scope: "general", Active: true, ReviewStatus: "published"}
	for _, k := range []*models.Knowledge{&a, &b} {
		if err := db.Create(k).Error; err != nil {
			t.Fatal(err)
		}
	}
	InvalidateKB(1)
	if knowledgePairConflicts(a, b) {
		t.Fatal("fixture unexpectedly caught by numeric conflict guard")
	}
	called, receivedOpposition := false, false
	s := &agentTurnState{userMessage: a.Question, knowledge: []models.Knowledge{a, b}, policy: responsePolicyForLength(selectAIResponsePolicy(a.Question, "", "", 1), "short", a.Question)}
	s.reviewAnswer = func(ctx context.Context, _, _, _ string) (answerEvidenceReview, error) {
		called = true
		rows, _ := ctx.Value(answerComparisonKey{}).([]map[string]any)
		for _, row := range rows {
			if row["source_id"] == b.ID {
				receivedOpposition = true
			}
		}
		// This spy models a reviewer that detects an opposing rule if given it.
		return answerEvidenceReview{Supported: !receivedOpposition, ConflictingSources: receivedOpposition}, nil
	}
	out := s.checkAnswer(context.Background(), 1, answerCheckInput{Answer: a.Answer, SourceIDs: []uint{a.ID}, Kind: "answer"})
	if !called {
		t.Fatalf("reviewer never called: %+v", out)
	}
	t.Logf("actual decision with visibility-sensitive spy: approved=%t issue=%q opposing_rule_received=%t", out.Approved, out.Issue, receivedOpposition)
	if !receivedOpposition {
		t.Error("BUG: unselected opposite policy absent from reviewer context for manual KB without source_url")
	}
}

func TestAgentGroundingRegressionComparisonKeepsRuleBeyondExcerpt(t *testing.T) {
	db := agenticTestDB(t)
	const restriction = "Paket Nusa tidak boleh dijual ulang."
	a := models.Knowledge{AgentID: 1, Question: "Apakah Paket Nusa boleh dijual ulang?", Answer: "Paket Nusa boleh dijual ulang.", SourceURL: "https://store.example/products/paket-nusa", Scope: "general", Active: true, ReviewStatus: "published"}
	b := models.Knowledge{AgentID: 1, Question: "Ketentuan Paket Nusa", Answer: strings.Repeat("Informasi penggunaan Paket Nusa. ", 100) + restriction, SourceURL: a.SourceURL, Scope: "general", Active: true, ReviewStatus: "published"}
	for _, k := range []*models.Knowledge{&a, &b} {
		if err := db.Create(k).Error; err != nil {
			t.Fatal(err)
		}
	}
	InvalidateKB(1)
	if !sameKnowledgeSubject(a, b) {
		t.Fatal("fixture not same subject")
	}
	var comparison []map[string]any
	s := &agentTurnState{userMessage: a.Question, knowledge: []models.Knowledge{a}, policy: responsePolicyForLength(selectAIResponsePolicy(a.Question, "", "", 1), "short", a.Question)}
	s.reviewAnswer = func(ctx context.Context, _, _, _ string) (answerEvidenceReview, error) {
		comparison, _ = ctx.Value(answerComparisonKey{}).([]map[string]any)
		return answerEvidenceReview{Supported: true}, nil
	}
	out := s.checkAnswer(context.Background(), 1, answerCheckInput{Answer: a.Answer, SourceIDs: []uint{a.ID}, Kind: "answer"})
	if len(comparison) != 1 {
		t.Fatalf("comparison spy not reached: output=%+v comparison=%+v", out, comparison)
	}
	answer, _ := comparison[0]["answer"].(string)
	t.Logf("stored_rule_bytes=%d comparison_bytes=%d approved=%t", len(b.Answer), len(answer), out.Approved)
	if !strings.Contains(answer, restriction) {
		t.Error("BUG: same-product comparison silently drops opposing rule after byte 2600, without a source_incomplete block")
	}
}

func TestAgentGroundingRegressionProductRestrictionBeyondClipIsVisible(t *testing.T) {
	db := agenticTestDB(t)
	if err := db.AutoMigrate(&models.Product{}); err != nil {
		t.Fatal(err)
	}
	const restriction = "Retur tidak berlaku untuk barang pesanan khusus."
	p := models.Product{AgentID: 1, TenantID: 1, Name: "Kaos Nusa", Price: "Rp75.000", Knowledge: "Kaos Nusa dapat diretur. " + strings.Repeat("Informasi katalog Kaos Nusa. ", 70) + restriction}
	if err := db.Create(&p).Error; err != nil {
		t.Fatal(err)
	}
	s := &agentTurnState{userMessage: "Apakah Kaos Nusa dapat diretur?", policy: responsePolicyForLength(selectAIResponsePolicy("retur?", "", "", 1), "short", "retur?")}
	tools, err := makeAgentTools(1, ChatOptions{DryRun: true}, s)
	if err != nil {
		t.Fatal(err)
	}
	var output string
	for _, base := range tools {
		info, err := base.Info(context.Background())
		if err != nil {
			t.Fatal(err)
		}
		if info.Name == "lookup_products" {
			output, err = base.(tool.InvokableTool).InvokableRun(context.Background(), `{"query":"Kaos Nusa"}`)
			if err != nil {
				t.Fatal(err)
			}
		}
	}
	if output == "" {
		t.Fatal("product tool unavailable")
	}
	if !strings.Contains(s.productFacts[p.ID].Knowledge, restriction) {
		t.Fatal("fixture missing full database snapshot")
	}
	t.Logf("full knowledge chars=%d tool sees restriction=%t truncation marker=%t", len([]rune(p.Knowledge)), strings.Contains(output, restriction), strings.Contains(output, "truncated"))
	var evidence string
	s.reviewAnswer = func(_ context.Context, _, _, supplied string) (answerEvidenceReview, error) {
		evidence = supplied
		return answerEvidenceReview{Supported: true}, nil
	}
	out := s.checkAnswer(context.Background(), 1, answerCheckInput{Answer: "Kaos Nusa dapat diretur.", Kind: "answer"})
	t.Logf("visibility spy reached=%t approved=%t issue=%q", evidence != "", out.Approved, out.Issue)
	if !strings.Contains(output, restriction) && !strings.Contains(output, "truncated") {
		t.Error("BUG: product tool silently drops the return exception without a truncation marker or product read tool")
	}
	if evidence != "" && !strings.Contains(evidence, restriction) {
		t.Error("BUG: independent answer reviewer also cannot see the stored return exception")
	}
	if out.Approved {
		t.Fatal("truncated product supported an answer before its full read")
	}
	s.userMessage = "Saya beli 1 Kaos Nusa."
	if _, issue := s.calculateTotal(context.Background(), 1, calculationInput{ProductID: p.ID, Quantity: 1, UnitPrice: 75000}); !strings.Contains(issue, "read_product") {
		t.Fatal("calculation did not require the full product terms", issue)
	}
	full, err := s.readProduct(context.Background(), 1, agentToolInput{ProductID: p.ID})
	if err != nil || full.Issue != "" || s.productIncomplete[p.ID] || !strings.Contains(s.businessEvidence, restriction) {
		t.Fatalf("full read lost product condition: result=%+v err=%v", full, err)
	}
	s.recordProduct(p, false)
	if s.productIncomplete[p.ID] || !strings.Contains(s.businessEvidence, restriction) {
		t.Fatal("a repeated search downgraded complete evidence")
	}
	if _, err := s.readProduct(context.Background(), 2, agentToolInput{ProductID: p.ID}); err == nil {
		t.Fatal("full read crossed agent boundary")
	}
}

func TestAgentGroundingRegressionReadCorrectionPreservesResolvedSubject(t *testing.T) {
	db := agenticTestDB(t)
	parent := models.Knowledge{AgentID: 1, Question: "Ketentuan Paket Nusa", Answer: "Ketentuan lama.", SourceURL: "https://store.example/products/paket-nusa", ReviewStatus: "archived", Scope: "general"}
	if err := db.Create(&parent).Error; err != nil {
		t.Fatal(err)
	}
	correction := models.Knowledge{AgentID: 1, Question: parent.Question, Answer: "Paket Nusa hanya untuk penggunaan internal. " + strings.Repeat("Lisensi Paket Nusa untuk penggunaan internal. ", 80), Source: "correction", SourceURL: "simulation://fixture", SupersedesID: parent.ID, ReviewStatus: "published", Active: true, Scope: "general"}
	if err := db.Create(&correction).Error; err != nil {
		t.Fatal(err)
	}
	resolved := []models.Knowledge{correction}
	if err := ResolveKnowledgeSubjects(db, 1, resolved); err != nil {
		t.Fatal(err)
	}
	if resolved[0].SubjectURL == "" {
		t.Fatal("fixture failed to inherit subject")
	}
	resolved[0].Answer = resolved[0].Answer[:2600]
	s := &agentTurnState{knowledge: resolved, userMessage: "Apa ketentuan Paket Nusa?"}
	if _, issue := s.freshAnswerSources(context.Background(), 1, []uint{correction.ID}); issue != "" {
		t.Fatalf("initial snapshot invalid: %q", issue)
	}
	tools, err := makeAgentTools(1, ChatOptions{DryRun: true}, s)
	if err != nil {
		t.Fatal(err)
	}
	read := false
	for _, base := range tools {
		info, err := base.Info(context.Background())
		if err != nil {
			t.Fatal(err)
		}
		if info.Name == "read_knowledge" {
			_, err = base.(tool.InvokableTool).InvokableRun(context.Background(), fmt.Sprintf(`{"source_id":%d}`, correction.ID))
			if err != nil {
				t.Fatal(err)
			}
			read = true
		}
	}
	if !read {
		t.Fatal("read tool missing")
	}
	t.Logf("after read: answer_bytes=%d subject_url=%q", len(s.knowledge[0].Answer), s.knowledge[0].SubjectURL)
	if _, issue := s.freshAnswerSources(context.Background(), 1, []uint{correction.ID}); issue != "" {
		t.Errorf("BUG: unchanged published correction becomes %q immediately after read_knowledge", issue)
	}
}
