"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const globals_1 = require("@jest/globals");
const ToolResponseCache_1 = require("../../src/processors/ToolResponseCache");
const services_1 = require("../../src/services");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
(0, globals_1.describe)("ToolResponseCache - MCP Format Support", () => {
    let cache;
    let toolsService;
    let githubJsonContent;
    (0, globals_1.beforeEach)(() => {
        toolsService = new services_1.ToolsService();
        cache = new ToolResponseCache_1.ToolResponseCache(toolsService);
        const githubJsonPath = path.join(__dirname, "githubjson.txt");
        githubJsonContent = fs.readFileSync(githubJsonPath, "utf-8");
    });
    (0, globals_1.describe)("MCP Format Detection and Storage", () => {
        (0, globals_1.it)("should detect and parse MCP format responses", () => {
            cache.storeToolResponse(githubJsonContent, "test-mcp-1");
            const stored = cache.retrieveRawResponse("test-mcp-1");
            (0, globals_1.expect)(stored).toBeDefined();
            (0, globals_1.expect)(stored).not.toBeNull();
            const parsed = JSON.parse(stored);
            (0, globals_1.expect)(parsed._mcp_format).toBe(true);
            (0, globals_1.expect)(parsed._data).toBeDefined();
            (0, globals_1.expect)(Array.isArray(parsed._data)).toBe(true);
        });
        (0, globals_1.it)("should preserve the data array in normalized structure", () => {
            cache.storeToolResponse(githubJsonContent, "test-mcp-2");
            const stored = cache.retrieveRawResponse("test-mcp-2");
            const parsed = JSON.parse(stored);
            (0, globals_1.expect)(parsed._data).toBeDefined();
            (0, globals_1.expect)(Array.isArray(parsed._data)).toBe(true);
            (0, globals_1.expect)(parsed._data.length).toBeGreaterThan(0);
            const firstRepo = parsed._data[0];
            (0, globals_1.expect)(firstRepo).toHaveProperty("id");
            (0, globals_1.expect)(firstRepo).toHaveProperty("name");
            (0, globals_1.expect)(firstRepo).toHaveProperty("full_name");
            (0, globals_1.expect)(firstRepo).toHaveProperty("owner");
        });
        (0, globals_1.it)("should store _mcp_format flag and _raw_structure metadata", () => {
            cache.storeToolResponse(githubJsonContent, "test-mcp-3");
            const stored = cache.retrieveRawResponse("test-mcp-3");
            const parsed = JSON.parse(stored);
            (0, globals_1.expect)(parsed._mcp_format).toBe(true);
            (0, globals_1.expect)(parsed._raw_structure).toBeDefined();
            (0, globals_1.expect)(parsed._raw_structure).toHaveProperty("content");
            (0, globals_1.expect)(Array.isArray(parsed._raw_structure.content)).toBe(true);
        });
    });
    (0, globals_1.describe)("JQ Queries Against MCP Data", () => {
        (0, globals_1.beforeEach)(() => {
            cache.storeToolResponse(githubJsonContent, "github-repos");
        });
        (0, globals_1.it)("should query the data array length with ._data | length", async () => {
            const result = await cache.queryToolResponse("github-repos", "._data | length");
            const length = JSON.parse(result);
            (0, globals_1.expect)(typeof length).toBe("number");
            (0, globals_1.expect)(length).toBeGreaterThan(0);
        });
        (0, globals_1.it)("should query first item in data array with ._data[0]", async () => {
            const result = await cache.queryToolResponse("github-repos", "._data[0]");
            const firstItem = JSON.parse(result);
            (0, globals_1.expect)(firstItem).toHaveProperty("id");
            (0, globals_1.expect)(firstItem).toHaveProperty("name");
            (0, globals_1.expect)(firstItem).toHaveProperty("full_name");
        });
        (0, globals_1.it)("should query specific field in first item with ._data[0].name", async () => {
            const result = await cache.queryToolResponse("github-repos", "._data[0].name");
            const name = JSON.parse(result);
            (0, globals_1.expect)(typeof name).toBe("string");
            (0, globals_1.expect)(name.length).toBeGreaterThan(0);
        });
        (0, globals_1.it)("should map over data array with ._data | map(.name)", async () => {
            const result = await cache.queryToolResponse("github-repos", "._data | map(.name)");
            const names = JSON.parse(result);
            (0, globals_1.expect)(Array.isArray(names)).toBe(true);
            (0, globals_1.expect)(names.length).toBeGreaterThan(0);
            (0, globals_1.expect)(typeof names[0]).toBe("string");
        });
        (0, globals_1.it)("should filter data array with ._data | map(select(.private == true))", async () => {
            const result = await cache.queryToolResponse("github-repos", "._data | map(select(.private == true))");
            const privateRepos = JSON.parse(result);
            (0, globals_1.expect)(Array.isArray(privateRepos)).toBe(true);
            privateRepos.forEach((repo) => {
                (0, globals_1.expect)(repo.private).toBe(true);
            });
        });
        (0, globals_1.it)("should access nested properties with ._data[0].owner.login", async () => {
            const result = await cache.queryToolResponse("github-repos", "._data[0].owner.login");
            const login = JSON.parse(result);
            (0, globals_1.expect)(typeof login).toBe("string");
            (0, globals_1.expect)(login.length).toBeGreaterThan(0);
        });
    });
    (0, globals_1.describe)("Non-MCP Format Compatibility", () => {
        (0, globals_1.it)("should handle plain JSON arrays without MCP wrapper", () => {
            const plainArray = JSON.stringify([
                { id: 1, name: "test1" },
                { id: 2, name: "test2" },
            ]);
            cache.storeToolResponse(plainArray, "plain-json");
            const stored = cache.retrieveRawResponse("plain-json");
            (0, globals_1.expect)(stored).toBe(plainArray);
            const parsed = JSON.parse(stored);
            (0, globals_1.expect)(parsed._mcp_format).toBeUndefined();
            (0, globals_1.expect)(Array.isArray(parsed)).toBe(true);
        });
        (0, globals_1.it)("should handle plain JSON objects without MCP wrapper", () => {
            const plainObject = JSON.stringify({ status: "success", data: { value: 42 } });
            cache.storeToolResponse(plainObject, "plain-object");
            const stored = cache.retrieveRawResponse("plain-object");
            (0, globals_1.expect)(stored).toBe(plainObject);
            const parsed = JSON.parse(stored);
            (0, globals_1.expect)(parsed._mcp_format).toBeUndefined();
            (0, globals_1.expect)(parsed.status).toBe("success");
        });
        (0, globals_1.it)("should handle plain text without JSON parsing", () => {
            const plainText = "This is just plain text, not JSON";
            cache.storeToolResponse(plainText, "plain-text");
            const stored = cache.retrieveRawResponse("plain-text");
            (0, globals_1.expect)(stored).toBe(plainText);
        });
        (0, globals_1.it)("should query plain JSON arrays with direct JQ queries", async () => {
            const plainArray = JSON.stringify([
                { id: 1, name: "test1" },
                { id: 2, name: "test2" },
            ]);
            cache.storeToolResponse(plainArray, "plain-array");
            const result = await cache.queryToolResponse("plain-array", ".[0].name");
            const name = JSON.parse(result);
            (0, globals_1.expect)(name).toBe("test1");
        });
    });
    (0, globals_1.describe)("Edge Cases and Double-Encoded JSON", () => {
        (0, globals_1.it)("should handle double-encoded JSON strings", () => {
            const data = { test: "value" };
            const doubleEncoded = JSON.stringify(JSON.stringify(data));
            cache.storeToolResponse(doubleEncoded, "double-encoded");
            const stored = cache.retrieveRawResponse("double-encoded");
            const parsed = JSON.parse(stored);
            (0, globals_1.expect)(parsed.test).toBe("value");
        });
        (0, globals_1.it)("should handle MCP format with double-encoded text field", () => {
            const innerData = [{ id: 1, value: "test" }];
            const doubleEncodedText = JSON.stringify(JSON.stringify(innerData));
            const mcpWrapper = JSON.stringify({
                content: [{ type: "text", text: doubleEncodedText }],
            });
            cache.storeToolResponse(mcpWrapper, "mcp-double-encoded");
            const stored = cache.retrieveRawResponse("mcp-double-encoded");
            const parsed = JSON.parse(stored);
            (0, globals_1.expect)(parsed._mcp_format).toBe(true);
            (0, globals_1.expect)(parsed._data).toBeDefined();
            (0, globals_1.expect)(Array.isArray(parsed._data)).toBe(true);
            (0, globals_1.expect)(parsed._data[0].value).toBe("test");
        });
        (0, globals_1.it)("should handle empty MCP content array", () => {
            const emptyMcp = JSON.stringify({
                content: [],
            });
            cache.storeToolResponse(emptyMcp, "empty-mcp");
            const stored = cache.retrieveRawResponse("empty-mcp");
            const parsed = JSON.parse(stored);
            (0, globals_1.expect)(parsed._mcp_format).toBeUndefined();
            (0, globals_1.expect)(parsed.content).toBeDefined();
            (0, globals_1.expect)(Array.isArray(parsed.content)).toBe(true);
            (0, globals_1.expect)(parsed.content.length).toBe(0);
        });
        (0, globals_1.it)("should handle MCP format with non-JSON text", () => {
            const mcpWithText = JSON.stringify({
                content: [{ type: "text", text: "This is plain text, not JSON" }],
            });
            cache.storeToolResponse(mcpWithText, "mcp-plain-text");
            const stored = cache.retrieveRawResponse("mcp-plain-text");
            const parsed = JSON.parse(stored);
            (0, globals_1.expect)(parsed._mcp_format).toBeUndefined();
            (0, globals_1.expect)(parsed.content[0].text).toBe("This is plain text, not JSON");
        });
        (0, globals_1.it)("should not overwrite stored responses on subsequent stores", () => {
            const originalData = JSON.stringify({ original: true });
            const newData = JSON.stringify({ original: false });
            cache.storeToolResponse(originalData, "no-overwrite");
            cache.storeToolResponse(newData, "no-overwrite");
            const stored = cache.retrieveRawResponse("no-overwrite");
            const parsed = JSON.parse(stored);
            (0, globals_1.expect)(parsed.original).toBe(true);
        });
    });
    (0, globals_1.describe)("Metadata and Storage Management", () => {
        (0, globals_1.it)("should track metadata for MCP format responses", () => {
            cache.storeToolResponse(githubJsonContent, "meta-test", "github_list_repos");
            const keys = cache.getStorageKeys();
            (0, globals_1.expect)(keys).toContain("meta-test");
            const size = cache.getStorageSize();
            (0, globals_1.expect)(size).toBeGreaterThanOrEqual(1);
        });
        (0, globals_1.it)("should list stored tool responses including MCP format", async () => {
            cache.storeToolResponse(githubJsonContent, "repo-list", "github_repos");
            cache.storeToolResponse(JSON.stringify({ test: "data" }), "test-data", "test_tool");
            const list = await cache.listStoredToolResponses();
            (0, globals_1.expect)(list).toContain("repo-list");
            (0, globals_1.expect)(list).toContain("test-data");
        });
        (0, globals_1.it)("should clear all stored responses", () => {
            cache.storeToolResponse(githubJsonContent, "clear-test-1");
            cache.storeToolResponse(JSON.stringify({ test: "data" }), "clear-test-2");
            (0, globals_1.expect)(cache.getStorageSize()).toBe(2);
            cache.clearStorage();
            (0, globals_1.expect)(cache.getStorageSize()).toBe(0);
            (0, globals_1.expect)(cache.retrieveRawResponse("clear-test-1")).toBeNull();
            (0, globals_1.expect)(cache.retrieveRawResponse("clear-test-2")).toBeNull();
        });
    });
});
//# sourceMappingURL=toolResponseCache.test.js.map