package services

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

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

// Models may stop before calling the required tools. Exercise recovery with the real Eino tools,
// including a rejected draft, instead of trusting a scripted approval flag.
type prematureAnswerModel struct {
	answerLoopModel
	calls    int
	stubborn bool
}

func TestAnswerAgentNativeDeepSeekRecoveryPreservesToolsAndReviewerIsolation(t *testing.T) {
	db := agenticTestDB(t)
	k := models.Knowledge{AgentID: 1, Question: "Apa syarat retur?", Answer: "Retur maksimal 7 hari dan barang belum dipakai.", Active: true, ReviewStatus: "published", Scope: "general"}
	if err := db.Create(&k).Error; err != nil {
		t.Fatal(err)
	}
	InvalidateKB(1)
	requests := 0
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		requests++
		var body struct {
			ToolChoice string            `json:"tool_choice"`
			Tools      []json.RawMessage `json:"tools"`
			Messages   []struct {
				Role      string `json:"role"`
				Content   string `json:"content"`
				Reasoning string `json:"reasoning_content"`
			} `json:"messages"`
			Thinking       map[string]string `json:"thinking"`
			MaxTokens      int               `json:"max_tokens"`
			ResponseFormat map[string]string `json:"response_format"`
		}
		if err := json.NewDecoder(req.Body).Decode(&body); err != nil {
			t.Error(err)
			w.WriteHeader(400)
			return
		}
		if requests <= 3 {
			if body.ToolChoice != "auto" || len(body.Tools) == 0 || body.Thinking["type"] != "enabled" {
				t.Error("native thinking requires automatic tool choice and bound tools")
			}
		} else if len(body.Tools) != 0 || body.Thinking["type"] != "disabled" || body.ToolChoice == "required" || body.MaxTokens > 4096 || body.ResponseFormat["type"] != "json_object" {
			t.Error("independent JSON reviewer inherited the planning budget or tools")
		}
		message := map[string]any{"role": "assistant", "reasoning_content": "private-native-reasoning", "content": ""}
		finish := "tool_calls"
		switch requests {
		case 1:
			message["content"] = "Retur selalu diterima tanpa syarat."
			finish = "stop"
		case 2:
			if !strings.Contains(body.Messages[0].Content, "LANJUTKAN PEMERIKSAAN") {
				t.Error("missing recovery instruction")
			}
			message["tool_calls"] = []schema.ToolCall{{ID: "search", Type: "function", Function: schema.FunctionCall{Name: "search_knowledge", Arguments: `{"query":"syarat retur"}`}}}
		case 3:
			preserved, result := false, false
			for _, item := range body.Messages {
				preserved = preserved || item.Role == "assistant" && item.Reasoning == "private-native-reasoning"
				result = result || item.Role == "tool" && strings.Contains(item.Content, "7 hari")
			}
			if !preserved || !result {
				t.Error("native tool context was discarded during recovery")
			}
			message["tool_calls"] = []schema.ToolCall{{ID: "check", Type: "function", Function: schema.FunctionCall{Name: "check_answer", Arguments: fmt.Sprintf(`{"answer":%q,"source_ids":[%d],"kind":"answer"}`, k.Answer, k.ID)}}}
		case 4:
			message["content"] = `{"supported":true,"requires_handoff":false,"unsupported_claims":[],"conflict":false,"complete":true,"missing_aspects":[],"conditions":[],"statements":[]}`
			finish = "stop"
		default:
			t.Error("approved answer was needlessly regenerated")
			message["content"] = "changed final"
			finish = "stop"
		}
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(map[string]any{"id": fmt.Sprint(requests), "choices": []any{map[string]any{"index": 0, "finish_reason": finish, "message": message}}})
	}))
	defer server.Close()
	p := aiPreset{Key: "deepseek", BaseURL: deepSeekBase, Model: "deepseek-flash", APIKey: "fixture-key"}
	cfg := nativeAIModelConfig(p, 2200, .2)
	cfg.BaseURL = server.URL
	cm, err := einomodel.NewChatModel(context.Background(), cfg)
	if err != nil {
		t.Fatal(err)
	}
	observed := &observedChatModel{inner: cm, provider: p.Key, modelName: p.Model}
	s := &agentTurnState{reviewAnswer: approveTestAnswer, userMessage: k.Question, policy: responsePolicyForLength(selectAIResponsePolicy(k.Question, "", "", 1), "short", k.Question)}
	s.reviewAnswer = modelAnswerReviewer(observed)
	tools, err := makeAgentTools(1, ChatOptions{DryRun: true}, s)
	if err != nil {
		t.Fatal(err)
	}
	store := NewSimulationLogStore(t.TempDir())
	id := NewSimulationID()
	r, err := store.Start(1, id, NewSimulationID(), nil)
	if err != nil {
		t.Fatal(err)
	}
	input := []*schema.Message{schema.SystemMessage("private-system-fixture"), schema.UserMessage(k.Question)}
	out, err := executeAnswerAgent(r.Context(context.Background()), observed, tools, input, s)
	if err != nil || out == nil || out.Content != k.Answer || requests != 4 || s.answerRecoveries != 1 {
		t.Fatalf("native recovery failed: requests=%d err=%v", requests, err)
	}
	if input[0].Content != "private-system-fixture" {
		t.Fatal("recovery mutated original history")
	}
	r.Finish("completed", map[string]any{"reply": out.Content})
	record, err := store.Read(1, id)
	if err != nil {
		t.Fatal(err)
	}
	recovered, ready := false, false
	for _, event := range record.Events {
		recovered = recovered || event.Stage == "answer_recovery"
		ready = ready || event.Stage == "answer_ready"
	}
	raw, _ := json.Marshal(record)
	if !recovered || !ready || strings.Contains(string(raw), "private-native-reasoning") || strings.Contains(string(raw), "private-system-fixture") || strings.Contains(string(raw), "selalu diterima") {
		t.Fatal("diagnostics missing or unchecked/private model content logged")
	}
}

func (m *prematureAnswerModel) WithTools([]*schema.ToolInfo) (model.ToolCallingChatModel, error) {
	return m, nil
}
func (m *prematureAnswerModel) Generate(ctx context.Context, in []*schema.Message, opts ...model.Option) (*schema.Message, error) {
	m.calls++
	if m.stubborn || m.calls == 1 {
		return schema.AssistantMessage("Retur selalu diterima tanpa syarat.", nil), nil
	}
	return m.answerLoopModel.Generate(ctx, in, opts...)
}

func TestAnswerAgentRecoversPrematureFinalAndUsesCheckedText(t *testing.T) {
	db := agenticTestDB(t)
	k := models.Knowledge{AgentID: 1, Question: "Apa syarat retur?", Answer: "Retur maksimal 7 hari dan barang belum dipakai.", Active: true, ReviewStatus: "published", Scope: "general"}
	if err := db.Create(&k).Error; err != nil {
		t.Fatal(err)
	}
	InvalidateKB(1)
	s := &agentTurnState{reviewAnswer: approveTestAnswer, userMessage: k.Question, policy: responsePolicyForLength(selectAIResponsePolicy(k.Question, "", "", 1), "short", k.Question)}
	tools, err := makeAgentTools(1, ChatOptions{DryRun: true}, s)
	if err != nil {
		t.Fatal(err)
	}
	cm := &prematureAnswerModel{answerLoopModel: answerLoopModel{sourceID: k.ID}}
	out, err := executeAnswerAgent(context.Background(), cm, tools, []*schema.Message{schema.UserMessage(k.Question)}, s)
	if err != nil || s.approved == nil || s.answerChecks != 2 || out == nil || out.Content != k.Answer {
		t.Fatalf("premature final bypassed recovery: calls=%d checks=%d approved=%t err=%v", cm.calls, s.answerChecks, s.approved != nil, err)
	}
	if cm.calls != 4 {
		t.Fatalf("checked answer unnecessarily regenerated: calls=%d", cm.calls)
	}
}

func TestAnswerAgentBoundsIgnoredToolCallsAndReportsMissingCheck(t *testing.T) {
	agenticTestDB(t)
	s := &agentTurnState{reviewAnswer: approveTestAnswer}
	tools, err := makeAgentTools(1, ChatOptions{DryRun: true}, s)
	if err != nil {
		t.Fatal(err)
	}
	cm := &prematureAnswerModel{stubborn: true}
	out, err := executeAnswerAgent(context.Background(), cm, tools, []*schema.Message{schema.UserMessage("Anda jual apa?")}, s)
	if err != nil || out == nil || !strings.Contains(out.Content, "[[ESCALATE]]") || s.handoffReason != "answer_validation_failed" || s.lastAnswerIssue != "answer_check_missing" {
		t.Fatalf("unchecked final was not diagnosed: handoff=%s issue=%s err=%v", s.handoffReason, s.lastAnswerIssue, err)
	}
	if cm.calls != 3 {
		t.Fatalf("recovery not bounded: calls=%d", cm.calls)
	}
}

func TestAnswerAgentHonorsHandoffAndCancellationBeforeFinalizing(t *testing.T) {
	agenticTestDB(t)
	s := &agentTurnState{reviewAnswer: approveTestAnswer, handoffReason: "customer_request", approved: &checkedAgentAnswer{input: answerCheckInput{Answer: "stale approval"}}}
	tools, err := makeAgentTools(1, ChatOptions{DryRun: true}, s)
	if err != nil {
		t.Fatal(err)
	}
	cm := &prematureAnswerModel{stubborn: true}
	out, err := executeAnswerAgent(context.Background(), cm, tools, []*schema.Message{schema.UserMessage("CS manusia")}, s)
	if err != nil || out == nil || !strings.Contains(out.Content, "[[ESCALATE]]") || cm.calls != 0 {
		t.Fatalf("handoff ignored: calls=%d err=%v", cm.calls, err)
	}
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	if _, err := executeAnswerAgent(ctx, cm, tools, []*schema.Message{schema.UserMessage("Halo")}, s); !errors.Is(err, context.Canceled) {
		t.Fatalf("cancellation ignored: %v", err)
	}
}
