// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
//
// SPDX-License-Identifier: LicenseRef-MutuaL-1.2

package mcp

import (
	"context"
	"reflect"
	"slices"
	"strings"
	"testing"
)

// tools.READ_TOOL.1 tools.SCHEMA.4 tools.RESPONSES.6
func TestCallToolACIDToolsReadTool1RejectsUnsupportedTargetBeforeCallingCooked(t *testing.T) {
	backend := &fakeBackend{}
	server := NewServer(backend, "test")

	_, err := server.CallReadTool(context.Background(), ReadArguments{Target: "meal_plan"})
	if err == nil {
		t.Fatal("CallReadTool() error = nil, want unsupported target error")
	}
	if err.Error() != `unsupported read target "meal_plan" (supported: shopping_list, recipes, recipe, example_recipes)` {
		t.Fatalf("CallReadTool() error = %q", err.Error())
	}
	if backend.readShoppingListCalls != 0 || backend.metadataCalls != 0 || backend.contentCalls != 0 {
		t.Fatalf(
			"backend calls = shopping list %d metadata %d content %d, want none",
			backend.readShoppingListCalls,
			backend.metadataCalls,
			backend.contentCalls,
		)
	}
}

// recipes.SAVE.10 tools.SCHEMA.4 tools.RESPONSES.6
func TestCallToolACIDRecipesSave10RejectsUnsupportedSourceBeforeCallingCooked(t *testing.T) {
	backend := &fakeBackend{}
	server := NewServer(backend, "test")

	_, _, err := server.callSaveRecipeTool(context.Background(), nil, SaveRecipeArguments{Source: "unsupported"})
	if err == nil {
		t.Fatal("callSaveRecipeTool() error = nil, want unsupported source error")
	}
	if err.Error() != `unsupported save_recipe source "unsupported" (supported: raw_text, prepared, url, draft, existing)` {
		t.Fatalf("callSaveRecipeTool() error = %q", err.Error())
	}
	if backend.saveCalls != 0 || backend.draftSaveCalls != 0 {
		t.Fatalf("save calls = prepared %d draft %d, want none", backend.saveCalls, backend.draftSaveCalls)
	}
}

// tools.SCHEMA.3 tools.SCHEMA.5 tools.SAVE_RECIPE_TOOL.1 tools.CHANGE_SHOPPING_LIST_TOOL.1
func TestToolDescriptionsACIDToolsSchema3And5DescribeCurrentLimits(t *testing.T) {
	read := readTool()
	for _, want := range []string{
		"shopping_list",
		"recipes",
		"recipe with recipe_id",
		"example_recipes",
		"You MUST check the examples before saving anything",
		"particular Markdown dialect",
		"Recipe results omit images and thumbnails",
	} {
		if !strings.Contains(read.Description, want) {
			t.Fatalf("read description missing %q: %q", want, read.Description)
		}
	}

	save := saveRecipeTool()
	for _, want := range []string{
		"raw text",
		"prepared markdown",
		"URL import",
		"reviewed URL-import draft",
		"existing recipe update",
		"URL imports will return a draft_id for review",
	} {
		if !strings.Contains(save.Description, want) {
			t.Fatalf("save_recipe description missing %q: %q", want, save.Description)
		}
	}

	shopping := changeShoppingListTool()
	for _, want := range []string{
		"add",
		"update_item",
		"replace_selection",
		"add_selection",
		"remove_selection",
		"remove",
		"clear",
		"Remove and clear are destructive",
		"put quantities before names",
	} {
		if !strings.Contains(shopping.Description, want) {
			t.Fatalf("change_shopping_list description missing %q: %q", want, shopping.Description)
		}
	}
	if strings.Contains(shopping.Description, "Simple read-output lines") {
		t.Fatalf("change_shopping_list description includes removed read-output guidance: %q", shopping.Description)
	}
}

// tools.SCHEMA.6
func TestChangeShoppingListToolACIDToolsSchema6ExposesProductGroupIDsAsOptionalNonNullableStringArray(t *testing.T) {
	schema := changeShoppingListInputSchema()
	property, ok := schema.Properties["product_group_ids"]
	if !ok {
		t.Fatal("product_group_ids schema missing")
	}
	if slices.Contains(schema.Required, "product_group_ids") {
		t.Fatalf("required fields = %#v, want product_group_ids optional", schema.Required)
	}
	if property.Type != "array" {
		t.Fatalf("product_group_ids type = %q, want array", property.Type)
	}
	if len(property.Types) != 0 {
		t.Fatalf("product_group_ids types = %#v, want none", property.Types)
	}
	if len(property.AnyOf) != 0 {
		t.Fatalf("product_group_ids anyOf = %#v, want none", property.AnyOf)
	}
	if property.Items == nil || property.Items.Type != "string" {
		t.Fatalf("product_group_ids items = %#v, want string items", property.Items)
	}

	resolved, err := schema.Resolve(nil)
	if err != nil {
		t.Fatalf("Resolve() error = %v", err)
	}
	if err := resolved.Validate(map[string]any{"action": "clear"}); err != nil {
		t.Fatalf("Validate() with omitted product_group_ids error = %v", err)
	}
	if err := resolved.Validate(map[string]any{"action": "clear", "product_group_ids": nil}); err == nil {
		t.Fatal("Validate() with null product_group_ids error = nil, want rejection")
	}
}

// tools.READ_TOOL.1 tools.SAVE_RECIPE_TOOL.3 tools.SAVE_RECIPE_TOOL.5 tools.SAVE_RECIPE_TOOL.6
func TestArgumentDescriptionsACIDToolsReadTool1AndSaveRecipeTool3And5And6PointToExampleRecipes(t *testing.T) {
	readTarget, ok := reflect.TypeFor[ReadArguments]().FieldByName("Target")
	if !ok {
		t.Fatal("ReadArguments.Target field missing")
	}
	if !strings.Contains(string(readTarget.Tag), "example_recipes") {
		t.Fatalf("ReadArguments.Target tag = %q, want example_recipes", readTarget.Tag)
	}

	saveMarkdown, ok := reflect.TypeFor[SaveRecipeArguments]().FieldByName("Markdown")
	if !ok {
		t.Fatal("SaveRecipeArguments.Markdown field missing")
	}
	for _, want := range []string{"example_recipes", "Cooked's markdown dialect"} {
		if !strings.Contains(string(saveMarkdown.Tag), want) {
			t.Fatalf("SaveRecipeArguments.Markdown tag missing %q: %q", want, saveMarkdown.Tag)
		}
	}
}
