package services

import (
	"context"
	"errors"
	"strings"
	"testing"

	"github.com/cloudwego/eino/components/model"
	"github.com/cloudwego/eino/schema"
)

type completenessReviewModel struct {
	model.ToolCallingChatModel
	reply   string
	err     error
	calls   int
	payload string
}

func (m *completenessReviewModel) Generate(_ context.Context, messages []*schema.Message, _ ...model.Option) (*schema.Message, error) {
	m.calls++
	m.payload = messages[len(messages)-1].Content
	return schema.AssistantMessage(m.reply, nil), m.err
}

func TestCompletenessReviewRejectsUnusableVerdicts(t *testing.T) {
	fields := []ServiceField{{Key: "destination", Label: "Alamat lengkap pengiriman", Type: "text", Required: true}}
	for _, tt := range []struct {
		name, reply      string
		err              error
		wantErr, partial bool
	}{
		{name: "partial", reply: `{"incomplete_fields":["destination"]}`, partial: true},
		{name: "complete", reply: `{"incomplete_fields":[]}`},
		{name: "unknown key", reply: `{"incomplete_fields":["invented"]}`, wantErr: true},
		{name: "missing verdict", reply: `{}`, wantErr: true},
		{name: "null verdict", reply: `{"incomplete_fields":null}`, wantErr: true},
		{name: "invalid JSON", reply: "complete", wantErr: true},
		{name: "unavailable", err: errors.New("provider unavailable"), wantErr: true},
	} {
		t.Run(tt.name, func(t *testing.T) {
			cm := &completenessReviewModel{reply: tt.reply, err: tt.err}
			draft := ServiceExtraction{Fields: map[string]ServiceFieldValue{}}
			err := reviewServiceCompleteness(context.Background(), cm, aiPreset{}, fields, map[string]string{"destination": "Kota Uji"}, &draft)
			if (err != nil) != tt.wantErr || (len(draft.IncompleteFields) > 0) != tt.partial {
				t.Fatalf("verdict accepted incorrectly: err=%v draft=%+v", err, draft)
			}
		})
	}
}

func TestCompletenessReviewChecksMergedDraftWithoutInternalMetadata(t *testing.T) {
	cm := &completenessReviewModel{reply: `{"incomplete_fields":["destination"]}`}
	fields := []ServiceField{
		{Key: "destination", Label: "Alamat lengkap", Type: "text", Required: true},
		{Key: "name", Label: "Nama", Type: "text", Required: true},
		{Key: "note", Label: "Catatan", Type: "text"},
	}
	// An optional incomplete value must not bypass checking required values.
	draft := ServiceExtraction{Fields: map[string]ServiceFieldValue{"name": {Value: "Rina"}}, IncompleteFields: []string{"note"}}
	err := reviewServiceCompleteness(context.Background(), cm, aiPreset{}, fields, map[string]string{"destination": "Kota Uji", "_source_destination": "internal proof"}, &draft)
	if err != nil || cm.calls != 1 || !strings.Contains(cm.payload, `"name":"Rina"`) || strings.Contains(cm.payload, "internal proof") {
		t.Fatalf("wrong merged review: err=%v payload=%s", err, cm.payload)
	}
	if len(draft.IncompleteFields) != 2 || draft.IncompleteFields[1] != "destination" {
		t.Fatal("existing partial value was not marked incomplete", draft)
	}
}

func TestCompletenessReviewSkipsDraftAlreadyKnownToBeIncomplete(t *testing.T) {
	cm := &completenessReviewModel{}
	fields := []ServiceField{{Key: "destination", Required: true}}
	draft := ServiceExtraction{Fields: map[string]ServiceFieldValue{}}
	if err := reviewServiceCompleteness(context.Background(), cm, aiPreset{}, fields, nil, &draft); err != nil || cm.calls != 0 {
		t.Fatal("missing required value should not need model review")
	}
	draft.IncompleteFields = []string{"destination"}
	if err := reviewServiceCompleteness(context.Background(), cm, aiPreset{}, fields, map[string]string{"destination": "Kota Uji"}, &draft); err != nil || cm.calls != 0 {
		t.Fatal("known partial required value should remain incomplete without model review")
	}
}
