package services

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

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

// Regression expectation: an insufficient_evidence request before any search
// is rejected by makeHandoffTool and must return to the planner for retrieval.
// No external network calls or persistent DB writes: intercepted HTTP + SQLite memory.
func TestAgentRuntimeRegressionPrematureHandoffMustRecoverSearch(t *testing.T) {
	db := agenticTestDB(t)
	if err := db.AutoMigrate(&models.AppSetting{}, &models.Agent{}, &models.Product{}); err != nil {
		t.Fatal(err)
	}
	if err := db.Create(&models.AppSetting{Key: "ai_provider", Value: "deepseek"}).Error; err != nil {
		t.Fatal(err)
	}
	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)
	t.Setenv("DEEPSEEK_API_KEY", "fixture-runtime-audit")
	t.Setenv("DEEPSEEK_MODEL", "deepseek-flash")
	calls := 0
	original := http.DefaultTransport
	t.Cleanup(func() { http.DefaultTransport = original })
	http.DefaultTransport = handoffTestTransport(func(req *http.Request) (*http.Response, error) {
		if req.URL.Host != "api.deepseek.com" || req.Method != http.MethodPost {
			return nil, fmt.Errorf("blocked unexpected fixture request")
		}
		calls++
		message := map[string]any{"role": "assistant", "content": "", "reasoning_content": "fixture thought"}
		finish := "tool_calls"
		switch calls {
		case 1:
			message["tool_calls"] = []schema.ToolCall{{ID: "premature_handoff", Type: "function", Function: schema.FunctionCall{Name: "request_handoff", Arguments: `{"reason":"insufficient_evidence","customer_message":"Saya teruskan pertanyaan retur ke tim ya, Kak."}`}}}
		case 2:
			message["tool_calls"] = []schema.ToolCall{{ID: "recover_search", Type: "function", Function: schema.FunctionCall{Name: "search_knowledge", Arguments: `{"query":"syarat retur"}`}}}
		case 3:
			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:
			finish = "stop"
			message["content"] = `{"supported":true,"requires_handoff":false,"unsupported_claims":[],"conflict":false,"complete":true,"missing_aspects":[],"conditions":[],"statements":[]}`
		default:
			return nil, fmt.Errorf("unexpected extra model call %d", calls)
		}
		raw, _ := json.Marshal(map[string]any{"id": fmt.Sprint(calls), "choices": []any{map[string]any{"index": 0, "finish_reason": finish, "message": message}}})
		return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(string(raw)))}, nil
	})
	result, err := chatAgentic(models.Agent{ID: 1, AgenticEnabled: true, ResponseLength: "short"}, "Asisten toko; jangan mengarang informasi.", "ramah", k.Question, nil, ChatOptions{Context: context.Background(), DryRun: true, LatestCustomerMessage: k.Question})
	t.Logf("provider_calls=%d escalate=%t reason=%s reply=%q answer_issue=%s tools=%s", calls, result.Escalate, result.HandoffReason, result.Reply, result.Trace.AnswerCheckIssue, result.Trace.ToolNames)
	if err != nil {
		t.Fatal(err)
	}
	if result.Escalate || result.Reply != k.Answer {
		t.Fatalf("rejected premature handoff terminated the graph instead of allowing search: calls=%d reason=%s issue=%s", calls, result.HandoffReason, result.Trace.AnswerCheckIssue)
	}
}

type graphBoundaryRegressionModel struct {
	calls    int
	sourceID uint
	answer   string
}

func (m *graphBoundaryRegressionModel) WithTools([]*schema.ToolInfo) (model.ToolCallingChatModel, error) {
	return m, nil
}
func (m *graphBoundaryRegressionModel) Stream(ctx context.Context, in []*schema.Message, opts ...model.Option) (*schema.StreamReader[*schema.Message], error) {
	out, err := m.Generate(ctx, in, opts...)
	if err != nil {
		return nil, err
	}
	return schema.StreamReaderFromArray([]*schema.Message{out}), nil
}
func (m *graphBoundaryRegressionModel) Generate(_ context.Context, _ []*schema.Message, _ ...model.Option) (*schema.Message, error) {
	m.calls++
	name := "read_knowledge"
	args := fmt.Sprintf(`{"source_id":%d}`, m.sourceID)
	if m.calls > 6 {
		name = "check_answer"
		draft := "Retur maksimal 999 hari dan barang belum dipakai."
		if m.calls == 10 {
			draft = m.answer
		}
		args = fmt.Sprintf(`{"answer":%q,"source_ids":[%d],"kind":"answer"}`, draft, m.sourceID)
	}
	return schema.AssistantMessage("", []schema.ToolCall{{ID: fmt.Sprint(m.calls), Type: "function", Function: schema.FunctionCall{Name: name, Arguments: args}}}), nil
}

func TestAgentRuntimeRegressionApprovedFinalAtGraphBoundaryMustSurvive(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)
	state := &agentTurnState{knowledge: []models.Knowledge{k}, userMessage: k.Question, reviewAnswer: approveTestAnswer, policy: responsePolicyForLength(selectAIResponsePolicy(k.Question, "", "", 1), "short", k.Question)}
	allTools, err := makeAgentTools(1, ChatOptions{DryRun: true}, state)
	if err != nil {
		t.Fatal(err)
	}
	planner := &graphBoundaryRegressionModel{sourceID: k.ID, answer: k.Answer}
	out, err := executeAnswerAgent(context.Background(), planner, allTools, []*schema.Message{schema.UserMessage(k.Question)}, state)
	t.Logf("planner_calls=%d data_calls=%d checks=%d semantic_reviews=%d approved=%t err=%v", planner.calls, state.calls, state.answerChecks, state.answerReviews, state.approved != nil, err)
	if err != nil || out == nil || out.Content != k.Answer {
		t.Fatalf("approved answer lost at graph boundary: approved=%t out=%v err=%v", state.approved != nil, out, err)
	}
}
