package services

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

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

// Reproduces the simulator's "belinya dimana" response: a source already
// contains the product URL, but the draft only tells the customer to find it.
func TestAgentPurchaseDirectionsRequireKnownLink(t *testing.T) {
	db := agenticTestDB(t)
	k := models.Knowledge{AgentID: 1, Question: "Bagaimana pembelian Source Code Toko Uji?", Answer: "Pembelian Source Code Toko Uji dilakukan melalui halaman produk di website resmi Toko Uji.", SourceURL: "https://store.example/p/source-code-toko-uji", Active: true, ReviewStatus: "published", Scope: "general"}
	if err := db.Create(&k).Error; err != nil {
		t.Fatal(err)
	}
	for _, mode := range []string{"short", "balanced", "detailed"} {
		t.Run(mode, func(t *testing.T) {
			s := &agentTurnState{reviewAnswer: approveTestAnswer, userMessage: "belinya dimana", knowledge: []models.Knowledge{k}, policy: responsePolicyForLength(selectAIResponsePolicy("belinya dimana", "", "", 1), mode, "belinya dimana")}
			s.reviewAnswer = func(context.Context, string, string, string) (answerEvidenceReview, error) {
				return answerEvidenceReview{Supported: true}, nil
			}
			in := answerCheckInput{Answer: "Pembelian Source Code Toko Uji dilakukan melalui website resmi Toko Uji, di halaman produknya.", SourceIDs: []uint{k.ID}, Kind: "answer"}
			out := s.checkAnswer(context.Background(), 1, in)
			if out.Issue != "action_link_required" || s.approved != nil || s.answerReviews != 0 {
				t.Fatalf("a website direction without its known URL must be repaired before model review: %+v", out)
			}
			if len(out.LinkHints) != 1 || out.LinkHints[0].URL != k.SourceURL || out.LinkHints[0].SourceID != k.ID {
				t.Fatalf("repair feedback omitted the verified destination: %+v", out)
			}
			in.Answer = "Pembelian Source Code Toko Uji melalui halaman produk ini:\n" + k.SourceURL
			out = s.checkAnswer(context.Background(), 1, in)
			if !out.Approved || s.approved.input.Answer != in.Answer || s.answerReviews != 1 {
				t.Fatalf("the verified URL should complete the answer within the selected length: %+v", out)
			}
		})
	}
}

func TestActionLinkChecksKeepCustomerRecallSeparateFromPurchaseEvidence(t *testing.T) {
	url := "https://customer.example/my-note"
	evidence := "Pelanggan sebelumnya mengatakan: " + url
	if issue, _ := checkActionLinks("Tadi saya kirim link apa?", "Tadi Anda mengirim tautan ini:\n"+url, evidence, "", nil); issue != "" {
		t.Fatalf("literal history recall must remain possible: %s", issue)
	}
	if issue, _ := checkActionLinks("Di mana belinya?", "Buka website ini untuk membeli:\n"+url, evidence, "", nil); issue != "unsupported_links" {
		t.Fatalf("customer history became a verified purchase destination: %s", issue)
	}
	if needsActionLink("Jelaskan cara checkout tanpa link", "Pembelian dilakukan melalui website resmi.") {
		t.Fatal("explicit preference to omit links was ignored")
	}
	if issue, _ := checkActionLinks("Cara checkout?", "Pembelian dilakukan melalui website resmi.", "Pembelian melalui website resmi.", "", nil); issue != "" {
		t.Fatalf("missing source URLs must not force an impossible rewrite: %s", issue)
	}
}

type actionLinkLoopModel struct {
	answerLoopModel
	url string
}

func (m *actionLinkLoopModel) WithTools([]*schema.ToolInfo) (model.ToolCallingChatModel, error) {
	return m, nil
}
func (m *actionLinkLoopModel) Generate(_ context.Context, in []*schema.Message, _ ...model.Option) (*schema.Message, error) {
	last := in[len(in)-1]
	name, args := "search_knowledge", `{"query":"pembelian Source Code Toko Uji"}`
	if last.Role == schema.Tool {
		answer := "Pembelian Source Code Toko Uji dilakukan melalui website resmi Toko Uji, di halaman produknya."
		if strings.Contains(last.Content, "action_link_required") {
			if !strings.Contains(last.Content, m.url) {
				return nil, fmt.Errorf("tool did not provide the known URL for repair")
			}
			answer = "Buka halaman produk Source Code Toko Uji untuk pembelian:\n" + m.url
		}
		name, args = "check_answer", fmt.Sprintf(`{"answer":%q,"source_ids":[%d],"kind":"answer"}`, answer, m.sourceID)
	}
	return schema.AssistantMessage("", []schema.ToolCall{{ID: fmt.Sprint(len(in)), Type: "function", Function: schema.FunctionCall{Name: name, Arguments: args}}}), nil
}

func TestEinoRepairsMissingPurchaseLinkWithoutExtraSearchOrHandoff(t *testing.T) {
	db := agenticTestDB(t)
	k := models.Knowledge{AgentID: 1, Question: "Pembelian Source Code Toko Uji?", Answer: "Pembelian Source Code Toko Uji dilakukan melalui halaman produk di website resmi Toko Uji.", SourceURL: "https://store.example/p/toko-uji", Active: true, ReviewStatus: "published", Scope: "general"}
	if err := db.Create(&k).Error; err != nil {
		t.Fatal(err)
	}
	InvalidateKB(1)
	s := &agentTurnState{reviewAnswer: approveTestAnswer, userMessage: "belinya dimana", policy: responsePolicyForLength(selectAIResponsePolicy("belinya dimana", "", "", 1), "short", "belinya dimana")}
	s.reviewAnswer = func(context.Context, string, string, string) (answerEvidenceReview, error) {
		return answerEvidenceReview{Supported: true}, nil
	}
	tools, err := makeAgentTools(1, ChatOptions{DryRun: true}, s)
	if err != nil {
		t.Fatal(err)
	}
	out, err := executeAnswerAgent(context.Background(), &actionLinkLoopModel{answerLoopModel: answerLoopModel{sourceID: k.ID}, url: k.SourceURL}, tools, []*schema.Message{schema.UserMessage(s.userMessage)}, s)
	if err != nil || out == nil || !strings.Contains(out.Content, k.SourceURL) || s.approved == nil || s.answerChecks != 2 || s.answerReviews != 1 || s.calls != 1 || s.handoffReason != "" {
		t.Fatalf("known link was not repaired using existing evidence: out=%v checks=%d reviews=%d calls=%d err=%v", out, s.answerChecks, s.answerReviews, s.calls, err)
	}
}

func TestAgentPurchaseLinksMustComeFromSelectedFreshEvidence(t *testing.T) {
	db := agenticTestDB(t)
	k := models.Knowledge{AgentID: 1, Question: "Cara checkout Toko Uji?", Answer: "Buka halaman produk Toko Uji untuk melanjutkan checkout.", SourceURL: "https://store.example/p/toko-uji", Active: true, ReviewStatus: "published", Scope: "general"}
	if err := db.Create(&k).Error; err != nil {
		t.Fatal(err)
	}
	s := &agentTurnState{reviewAnswer: approveTestAnswer, userMessage: k.Question, knowledge: []models.Knowledge{k}, policy: responsePolicyForLength(selectAIResponsePolicy(k.Question, "", "", 1), "short", k.Question)}
	s.reviewAnswer = func(context.Context, string, string, string) (answerEvidenceReview, error) {
		return answerEvidenceReview{Supported: true}, nil
	}
	for _, fake := range []string{"https://store.example/checkout", "https://other.example/p/toko-uji", k.SourceURL + "?payment=external"} {
		out := s.checkAnswer(context.Background(), 1, answerCheckInput{Answer: "Buka halaman produk Toko Uji untuk checkout:\n" + fake, SourceIDs: []uint{k.ID}, Kind: "answer"})
		if out.Issue != "unsupported_links" || s.approved != nil {
			t.Fatalf("invented URL passed even though its words have no unsupported numbers: %+v", out)
		}
	}
	if err := db.Model(&k).UpdateColumn("source_url", "https://store.example/p/new-page").Error; err != nil {
		t.Fatal(err)
	}
	out := s.checkAnswer(context.Background(), 1, answerCheckInput{Answer: "Buka halaman produk Toko Uji:\n" + k.SourceURL, SourceIDs: []uint{k.ID}, Kind: "answer"})
	if out.Issue != "source_changed" {
		t.Fatalf("a URL changed without updated_at must still invalidate the snapshot: %+v", out)
	}
}

func TestAgentLinksDoNotPadUnrelatedAnswersOrInventMissingDestinations(t *testing.T) {
	db := agenticTestDB(t)
	k := models.Knowledge{AgentID: 1, Question: "Jam layanan dan cara memesan Toko Uji?", Answer: "Layanan buka Senin sampai Jumat. Pembelian dapat diproses melalui chat ini.", SourceURL: "https://store.example", Active: true, ReviewStatus: "published", Scope: "general"}
	if err := db.Create(&k).Error; err != nil {
		t.Fatal(err)
	}
	for _, tc := range []struct{ question, answer, kind string }{
		{"Jam layanannya?", "Layanan buka Senin sampai Jumat.", "answer"},
		{"Cara memesan?", "Pembelian dapat diproses melalui chat ini.", "answer"},
		{"Cara checkout?", "Produk yang mana yang ingin dibeli?", "clarification"},
	} {
		s := &agentTurnState{reviewAnswer: approveTestAnswer, userMessage: tc.question, knowledge: []models.Knowledge{k}, policy: responsePolicyForLength(selectAIResponsePolicy(tc.question, "", "", 1), "short", tc.question)}
		out := s.checkAnswer(context.Background(), 1, answerCheckInput{Answer: tc.answer, SourceIDs: []uint{k.ID}, Kind: tc.kind})
		if !out.Approved || strings.Contains(s.approved.input.Answer, "https://") {
			t.Fatalf("irrelevant links were forced into a valid answer: %+v", out)
		}
	}
	// With no known URL, this guard must not start an endless rewrite/handoff
	// loop. The planner can search for the destination or ask for clarification.
	k.SourceURL = ""
	if err := db.Save(&k).Error; err != nil {
		t.Fatal(err)
	}
	s := &agentTurnState{reviewAnswer: approveTestAnswer, userMessage: "Jam layanannya?", knowledge: []models.Knowledge{k}, policy: responsePolicyForLength(selectAIResponsePolicy("Jam layanannya?", "", "", 1), "short", "Jam layanannya?")}
	if out := s.checkAnswer(context.Background(), 1, answerCheckInput{Answer: "Layanan buka Senin sampai Jumat.", SourceIDs: []uint{k.ID}, Kind: "answer"}); !out.Approved {
		t.Fatal(out)
	}
}
