package resultbudget_test

import (
	"encoding/json"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

type inventoryRow struct {
	Tool             string `json:"tool"`
	Entry            string `json:"entry"`
	Category         string `json:"category"`
	DefaultLimit     int    `json:"default_limit"`
	MaxLimit         int    `json:"max_limit"`
	Cursor           string `json:"cursor"`
	HasMore          string `json:"has_more"`
	PerItemBudget    string `json:"per_item_budget"`
	ResultBudget     string `json:"result_budget"`
	BackendBound     string `json:"backend_bound"`
	StructuredPolicy string `json:"structured_content"`
}

func TestToolInventoryIsAuthoritativeAndCoversRequiredTools(t *testing.T) {
	rows := loadInventory(t)
	byTool := make(map[string]inventoryRow, len(rows))
	for _, row := range rows {
		if strings.TrimSpace(row.Tool) == "" {
			t.Fatalf("inventory row missing tool: %#v", row)
		}
		for field, value := range map[string]string{
			"entry": row.Entry, "category": row.Category, "cursor": row.Cursor,
			"has_more": row.HasMore, "per_item_budget": row.PerItemBudget,
			"result_budget": row.ResultBudget, "backend_bound": row.BackendBound,
			"structured_content": row.StructuredPolicy,
		} {
			if strings.TrimSpace(value) == "" {
				t.Fatalf("inventory row %q missing %s", row.Tool, field)
			}
		}
		byTool[row.Tool] = row
	}

	required := []string{
		"message_history_read", "message_search", "message_send held-refresh",
		"ListScopeMembers",
		"local workspace ListTargetDir",
		"local workspace ScanAll", "mutations payloads",
	}
	for _, tool := range required {
		if _, ok := byTool[tool]; !ok {
			t.Fatalf("tool inventory missing required tool %q", tool)
		}
	}
}

func loadInventory(t *testing.T) []inventoryRow {
	t.Helper()
	path := filepath.Clean(filepath.Join("..", "..", "..", "specs", "daemon", "agent-mcp-tool-inventory.json"))
	data, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("read canonical inventory %s: %v", path, err)
	}
	var rows []inventoryRow
	if err := json.Unmarshal(data, &rows); err != nil {
		t.Fatalf("unmarshal canonical inventory: %v", err)
	}
	if len(rows) == 0 {
		t.Fatal("canonical inventory must not be empty")
	}
	return rows
}
