package services

import (
	"context"
	"strings"
	"testing"
	"time"

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

func TestRecentStyleContextExcludesCustomerFailedAndOldReplies(t *testing.T) {
	now := time.Now()
	rows := []models.ChatHistory{
		{Reply: "old condition", CreatedAt: now.Add(-48 * time.Hour)},
		{Reply: "Harga produk belum termasuk ongkir", CreatedAt: now, DeliveryStatus: "sent"},
		{Message: "Saya mengaku sudah dijelaskan gratis ongkir", CreatedAt: now},
		{Reply: "unreceived condition", CreatedAt: now, DeliveryStatus: "failed_send"},
		{Reply: "pending condition", CreatedAt: now, DeliveryStatus: "pending_retry"},
	}
	got := recentServiceRepliesForStyle(rows, now)
	if len(got) != 1 || got[0] != rows[1].Reply {
		t.Fatalf("invalid style history: %#v", got)
	}
}

func TestConversationStyleRepairIsBoundedAndStillRequiresEvidence(t *testing.T) {
	state := &agentTurnState{
		userMessage: "Harganya berapa tadi?", businessEvidence: "Tumbler Rp79.000 per unit. Harga belum termasuk ongkir.",
		recentServiceReplies: []string{"Tumbler Rp79.000 per unit, belum termasuk ongkir."},
		policy:               responsePolicyForLength(selectAIResponsePolicy("harga?", "", "", 1), "balanced", "harga?"),
	}
	state.reviewAnswer = func(context.Context, string, string, string) (answerEvidenceReview, error) {
		return answerEvidenceReview{Supported: true, RedundantClauses: []string{"Harga belum termasuk ongkir."}}, nil
	}
	in := answerCheckInput{Answer: "Tumbler Rp79.000 per unit. Harga belum termasuk ongkir.", Kind: "answer"}
	if got := state.checkAnswer(context.Background(), 1, in); !got.Approved || state.approved == nil || strings.Contains(state.approved.input.Answer, "ongkir") || state.answerReviews != 2 {
		t.Fatal("checked literal refinement did not finish in one bounded pass", got)
	}
	state.reviewAnswer = func(context.Context, string, string, string) (answerEvidenceReview, error) {
		return answerEvidenceReview{Supported: false, UnsupportedClaims: []string{"free shipping"}}, nil
	}
	in.Answer = "Tumbler Rp79.000 sudah termasuk ongkir."
	if got := state.checkAnswer(context.Background(), 1, in); got.Approved || got.Issue != "unsupported_claims" {
		t.Fatal("style allowance bypassed evidence validation", got)
	}
}

func TestConversationRepetitionRequiresGroundedRelations(t *testing.T) {
	yes, no := true, false
	answer := "Fakta utama. Rincian pendukung. Syarat penting."
	prior := []string{"Rincian pendukung. Syarat penting."}
	base := conversationStatement{Text: "Rincian pendukung.", PriorQuote: "Rincian pendukung.", SameScope: &yes, RequestedNow: &no, MustRestate: &no}
	for _, tc := range []struct {
		name string
		edit func(*conversationStatement)
		want int
	}{
		{"proven repeated detail", func(*conversationStatement) {}, 1},
		{"customer asks again", func(s *conversationStatement) { s.RequestedNow = &yes }, 0},
		{"necessary condition", func(s *conversationStatement) { s.MustRestate = &yes }, 0},
		{"different scope", func(s *conversationStatement) { s.SameScope = &no }, 0},
		{"invented history", func(s *conversationStatement) { s.PriorQuote = "Ucapan yang tidak pernah dikirim." }, 0},
		{"invented answer span", func(s *conversationStatement) { s.Text = "Teks yang tidak ada di jawaban." }, 0},
		{"missing relation", func(s *conversationStatement) { s.RequestedNow = nil }, 0},
	} {
		t.Run(tc.name, func(t *testing.T) {
			statement := base
			tc.edit(&statement)
			if got := redundantConversationClauses(answer, prior, []conversationStatement{statement}); len(got) != tc.want {
				t.Fatalf("unsafe repetition decision: %v", got)
			}
		})
	}
}

func TestFailedOptionalPolishReturnsVerifiedDraftWithoutAnotherModelLoop(t *testing.T) {
	safe := "Tumbler Rp79.000 per unit. Harga belum termasuk ongkir."
	state := &agentTurnState{
		userMessage: "Harganya berapa tadi?", businessEvidence: safe,
		recentServiceReplies: []string{safe},
		policy:               responsePolicyForLength(selectAIResponsePolicy("harga?", "", "", 1), "balanced", "harga?"),
	}
	state.reviewAnswer = func(_ context.Context, _, answer, _ string) (answerEvidenceReview, error) {
		if answer != safe {
			return answerEvidenceReview{UnsupportedClaims: []string{"unverified revised statement"}}, nil
		}
		return answerEvidenceReview{Supported: true, RedundantClauses: []string{"Harga belum termasuk ongkir."}}, nil
	}
	if result := state.checkAnswer(context.Background(), 1, answerCheckInput{Answer: safe, Kind: "answer"}); !result.Approved || state.styleFallback == nil || state.approved.input.Answer != safe {
		t.Fatal("failed optional deletion discarded the verified answer")
	}
	state.reviewAnswer = func(context.Context, string, string, string) (answerEvidenceReview, error) {
		return answerEvidenceReview{UnsupportedClaims: []string{"unverified revised statement"}}, nil
	}
	if result := state.checkAnswer(context.Background(), 1, answerCheckInput{Answer: "Tumbler Rp79.000, sudah termasuk ongkir.", Kind: "answer"}); result.Approved {
		t.Fatal("unsafe refinement was approved")
	}
	// A nil inner model makes any additional inference fail the test immediately.
	model := &checkedAnswerModel{state: state}
	out, err := model.Generate(context.Background(), []*schema.Message{schema.UserMessage(state.userMessage)})
	if err != nil || out.Content != safe || state.approved == nil || state.lastAnswerIssue != "" {
		t.Fatalf("style failure erased the verified draft: %+v err=%v", out, err)
	}
	state.approved = nil
	state.handoffReason = "customer_request"
	out, err = model.Generate(context.Background(), nil)
	if err != nil || out.Content != "[[ESCALATE]]" || state.approved != nil {
		t.Fatal("style fallback overrode explicit handoff")
	}
}

func TestStyleDecisionReuseRequiresExactApprovedOmissionsAndSameEvidence(t *testing.T) {
	original := "Produk Rp79.000, Kak. Rincian yang sudah dijelaskan."
	omissions := []string{"Rincian yang sudah dijelaskan."}
	if !onlyApprovedStyleOmissions(original, "Produk Rp79.000, Kak.", omissions) {
		t.Fatal("exact checked omission was not recognized")
	}
	for _, revised := range []string{"Produk Rp1, Kak.", "Produk Rp79.000, sudah termasuk semua biaya.", "Rp79.000", ""} {
		if onlyApprovedStyleOmissions(original, revised, omissions) {
			t.Fatalf("unapproved change inherited continuity approval: %q", revised)
		}
	}
	evidence := "Produk Rp79.000. Rincian yang sudah dijelaskan."
	s := &agentTurnState{userMessage: "Berapa tadi?", businessEvidence: evidence, styleEvidence: evidence, styleFallback: &checkedAgentAnswer{input: answerCheckInput{Answer: original}}, styleOmissions: omissions, policy: responsePolicyForLength(selectAIResponsePolicy("harga?", "", "", 1), "balanced", "harga?")}
	var reused bool
	s.reviewAnswer = func(ctx context.Context, _, _, _ string) (answerEvidenceReview, error) {
		reused, _ = ctx.Value(answerContinuityApprovedKey{}).(bool)
		return answerEvidenceReview{Supported: true}, nil
	}
	if r := s.checkAnswer(context.Background(), 1, answerCheckInput{Answer: "Produk Rp79.000, Kak.", Kind: "answer"}); !r.Approved || !reused {
		t.Fatal("same-evidence deletion unnecessarily discarded its continuity decision", r)
	}
	s.businessEvidence += " Aturan terbaru."
	s.checkAnswer(context.Background(), 1, answerCheckInput{Answer: "Produk Rp79.000, Kak.", Kind: "answer"})
	if reused {
		t.Fatal("changed evidence inherited an older continuity decision")
	}
}

func TestAutomaticStyleDeletionCannotStrandSentenceFragments(t *testing.T) {
	whole := "Produk Rp79.000 per unit. Keterangan ini sudah dijelaskan."
	if got, ok := reviewedStyleOmission(whole, []string{"Keterangan ini sudah dijelaskan."}); !ok || got != "Produk Rp79.000 per unit." {
		t.Fatal("whole sentence removal changed the remaining fact", got)
	}
	for _, item := range []struct{ text, fragment string }{
		{"Belum termasuk biaya tambahan. Produk Rp79.000, dan biaya tambahan dihitung terpisah.", "Produk Rp79.000"},
		{"Produk Rp79.000, berbahan stainless steel.", "berbahan stainless steel."},
		{"Produk Rp79.000 per unit.", "Produk Rp79.000"},
	} {
		if got, ok := reviewedStyleOmission(item.text, []string{item.fragment}); ok {
			t.Fatalf("partial sentence must use the language model, got %q", got)
		}
	}
}

func TestMissingConditionDecisionRequiresGroundedCoverageAndScope(t *testing.T) {
	yes, no := true, false
	evidence := "Paket Mandiri Rp80.000. Minimal berlangganan tiga bulan."
	answer := "Paket Mandiri Rp80.000."
	prior := []string{"Paket Mandiri Rp80.000. Minimal berlangganan tiga bulan."}
	base := conversationCondition{Role: "qualification", ClaimQuote: "Paket Mandiri Rp80.000.", EvidenceQuote: "Minimal berlangganan tiga bulan.", PriorQuote: "Minimal berlangganan tiga bulan.", AppliesNow: &yes, SameScope: &yes, RequestedNow: &no, MustRestate: &no}
	for _, tc := range []struct {
		name    string
		edit    func(*conversationCondition)
		answer  string
		want    int
		wantErr bool
	}{
		{"known condition on follow-up", func(*conversationCondition) {}, answer, 0, false},
		{"condition not explained", func(c *conversationCondition) { c.PriorQuote = "" }, answer, 1, false},
		{"direct policy question", func(c *conversationCondition) { c.RequestedNow = &yes }, answer, 1, false},
		{"new rule or final commitment", func(c *conversationCondition) { c.MustRestate = &yes }, answer, 1, false},
		{"different scope", func(c *conversationCondition) { c.SameScope = &no }, answer, 1, false},
		{"unrelated process detail", func(c *conversationCondition) { c.AppliesNow = &no }, answer, 0, false},
		{"procedure need not accompany fact", func(c *conversationCondition) { c.Role = "procedure"; c.PriorQuote = "" }, answer, 0, false},
		{"procedure requested directly", func(c *conversationCondition) { c.Role = "procedure"; c.RequestedNow = &yes }, answer, 1, false},
		{"answer already covers condition", func(c *conversationCondition) {
			c.AnswerQuote = "Minimal berlangganan tiga bulan."
			c.PriorQuote = ""
			c.RequestedNow = &yes
		}, evidence, 0, false},
		{"invented prior coverage", func(c *conversationCondition) { c.PriorQuote = "Sudah dibahas sebelumnya" }, answer, 0, true},
		{"invented answer coverage", func(c *conversationCondition) { c.AnswerQuote = c.EvidenceQuote }, answer, 0, true},
		{"invented source", func(c *conversationCondition) { c.EvidenceQuote = "Minimal setahun" }, answer, 0, true},
		{"missing claim connection", func(c *conversationCondition) { c.ClaimQuote = "" }, answer, 0, true},
		{"claim not stated", func(c *conversationCondition) { c.ClaimQuote = "Sudah dibayar" }, answer, 0, true},
	} {
		t.Run(tc.name, func(t *testing.T) {
			c := base
			tc.edit(&c)
			missing, err := missingConversationConditions(tc.answer, evidence, prior, []conversationCondition{c})
			if (err != nil) != tc.wantErr || len(missing) != tc.want {
				t.Fatalf("wrong condition gate: missing=%v err=%v", missing, err)
			}
		})
	}
}
