package dev.sonpx.loyalty.agent.service;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;

class ToolResultPresentationProcessorTest {

    private final ObjectMapper objectMapper = new ObjectMapper();
    private final ToolResultPresentationProcessor processor = new ToolResultPresentationProcessor(objectMapper);

    @Test
    void leavesPlainTextResultsUnchanged() {
        String result = processor.process("done");
        assertEquals("done", result);
    }

    @Test
    void extractsAgentInstructionFromDirectJsonResult() throws Exception {
        String toolResult = """
                {
                  "data": [{"id": "1"}],
                  "_agent_instruction": "Format this list of campaigns as a markdown table."
                }
                """;

        String result = processor.process(toolResult);
        JsonNode sanitized = objectMapper.readTree(result);

        assertFalse(sanitized.has("_agent_instruction"));
        assertTrue(sanitized.has("agent_instruction"));
        assertEquals("Format this list of campaigns as a markdown table.", sanitized.get("agent_instruction").asText());
        assertTrue(sanitized.has("data"));
    }

    @Test
    void extractsAgentInstructionFromMcpTextResult() throws Exception {
        String innerResult = objectMapper.writeValueAsString(objectMapper.readTree("""
                {
                  "data": [{"id": "1"}],
                  "_agent_instruction": "Format this list of campaigns as a markdown table."
                }
                """));
        String toolResult = objectMapper.writeValueAsString(new Object[] {
                java.util.Map.of("type", "text", "text", innerResult)
        });

        String result = processor.process(toolResult);
        JsonNode root = objectMapper.readTree(result);
        JsonNode sanitizedInner = objectMapper.readTree(root.get(0).get("text").asText());

        assertFalse(sanitizedInner.has("_agent_instruction"));
        assertTrue(sanitizedInner.has("agent_instruction"));
        assertEquals("Format this list of campaigns as a markdown table.", sanitizedInner.get("agent_instruction").asText());
    }

    @Test
    void ignoresNonTextualAgentInstruction() throws Exception {
        String toolResult = """
                {
                  "data": [{"id": "1"}],
                  "_agent_instruction": {"nested": "value"}
                }
                """;

        String result = processor.process(toolResult);
        JsonNode parsed = objectMapper.readTree(result);

        assertTrue(parsed.has("_agent_instruction"));
        assertFalse(parsed.has("agent_instruction"));
    }
}
