package runtime

import (
	"encoding/json"
	"fmt"
	"strings"
)

func projectedExplorationToolMessage(callID, functionName string) (InferenceMessage, error) {
	var content string
	switch functionName {
	case knowledgeSearchFunction:
		content = strings.Repeat(`\`, maxSearchResultBytes)
	case knowledgeListFunction:
		content = strings.Repeat(`\`, maxListResultBytes)
	case knowledgeReadFunction:
		projected, err := json.Marshal(explorationReadResult{
			OK: true,
			Evidence: &explorationReadEvidence{
				ID: "E128", FileRef: strings.Repeat("f", maxReferenceBytes),
				Path:      strings.Repeat("\x00", maxListResultBytes),
				LineStart: 1, LineEnd: maxReadLines,
				Content: strings.Repeat("\x00", maxReadResultBytes),
			},
			Truncated: true,
		})
		if err != nil {
			return InferenceMessage{}, fmt.Errorf("encode projected Knowledge Q&A read result: %w", err)
		}
		content = string(projected)
	case knowledgeWebSearchFunction:
		content = strings.Repeat(`\`, maxSearchResultBytes)
	case knowledgeWebReadFunction:
		projected, err := json.Marshal(explorationWebReadResult{
			OK: true,
			Evidence: &explorationWebReadEvidence{
				ID: "E128", WebRef: strings.Repeat("w", maxReferenceBytes),
				Title: strings.Repeat("\x00", 1024), URL: "https://example.com/",
				Source: "example.com", FetchedAt: "2026-08-04T00:00:00Z",
				Content: strings.Repeat("\x00", maxReadResultBytes),
			},
			Truncated: true,
		})
		if err != nil {
			return InferenceMessage{}, fmt.Errorf("encode projected Knowledge Q&A web read result: %w", err)
		}
		content = string(projected)
	case knowledgeRefFunction:
		projected, err := json.Marshal(explorationRefResult{
			OK: true, RootAlias: strings.Repeat("r", maxReferenceBytes),
			Ref: strings.Repeat("b", maxRefNameBytes), RefType: RefKindBranch,
		})
		if err != nil {
			return InferenceMessage{}, fmt.Errorf("encode projected Knowledge Q&A ref result: %w", err)
		}
		content = string(projected)
	default:
		return InferenceMessage{}, invalidModelResponse()
	}
	return InferenceMessage{Role: "tool", ToolCallID: callID, Content: content}, nil
}

func explorationBatchTooLargeMessages(calls []InferenceToolCall) ([]InferenceMessage, int) {
	const content = `{"ok":false,"error":"batch_too_large","hint":"retry with fewer calls in one response"}`
	messages := make([]InferenceMessage, 0, len(calls))
	for _, call := range calls {
		messages = append(messages, InferenceMessage{Role: "tool", ToolCallID: call.ID, Content: content})
	}
	return messages, len(content) * len(messages)
}
