"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 Base64ImageDetector_1 = require("../../src/processors/Base64ImageDetector");
const Tools_1 = require("../../src/services/Tools");
const fs = __importStar(require("fs"));
describe("Base64ImageDetector", () => {
    let detector;
    beforeEach(() => {
        detector = new Base64ImageDetector_1.Base64ImageProcessor();
    });
    describe("Constructor", () => {
        it("should create instance with default parameters", () => {
            const instance = new Base64ImageDetector_1.Base64ImageProcessor();
            expect(instance).toBeInstanceOf(Base64ImageDetector_1.Base64ImageProcessor);
        });
        it("should create instance with custom image detail", () => {
            const instance = new Base64ImageDetector_1.Base64ImageProcessor();
            instance.setImageDetail("high");
            expect(instance).toBeInstanceOf(Base64ImageDetector_1.Base64ImageProcessor);
        });
        it("should create instance with custom supported formats", () => {
            const instance = new Base64ImageDetector_1.Base64ImageProcessor();
            instance.setImageDetail("low");
            instance.setSupportedFormats(["png", "jpeg"]);
            expect(instance).toBeInstanceOf(Base64ImageDetector_1.Base64ImageProcessor);
        });
    });
    describe("Configuration methods", () => {
        it("should allow setting image detail", () => {
            detector.setImageDetail("high");
            expect(() => detector.setImageDetail("high")).not.toThrow();
        });
        it("should allow setting supported formats", () => {
            detector.setSupportedFormats(["png", "jpeg"]);
            expect(() => detector.setSupportedFormats(["png", "jpeg"])).not.toThrow();
        });
    });
    describe("createProcessor", () => {
        it("should return a function", () => {
            const processor = detector.createProcessor();
            expect(typeof processor).toBe("function");
        });
        it("should process messages without throwing", () => {
            const processor = detector.createProcessor();
            const originalMessages = [];
            const modifiedMessages = [];
            expect(() => processor(originalMessages, modifiedMessages)).not.toThrow();
        });
    });
    describe("String content processing", () => {
        const validPngBase64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==";
        const validJpegBase64 = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVR";
        const plainBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==";
        const regularText = "This is just regular text";
        it("should convert data URL base64 string to image content", () => {
            const originalMessages = [];
            const modifiedMessages = [
                {
                    role: "user",
                    content: validPngBase64,
                },
            ];
            const processor = detector.createProcessor();
            processor(originalMessages, modifiedMessages);
            expect(Array.isArray(modifiedMessages[0].content)).toBe(true);
            const content = modifiedMessages[0].content;
            expect(content[0]).toEqual({
                type: "image_url",
                image_url: {
                    url: validPngBase64,
                    detail: "auto",
                },
            });
        });
        it("should convert plain base64 PNG to image content", () => {
            const originalMessages = [];
            const modifiedMessages = [
                {
                    role: "user",
                    content: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==",
                },
            ];
            const processor = detector.createProcessor();
            processor(originalMessages, modifiedMessages);
            if (Array.isArray(modifiedMessages[0].content)) {
                const content = modifiedMessages[0].content;
                expect(content[0].type).toBe("image_url");
                expect(content[0].image_url.url).toContain("data:image/png;base64,");
            }
            else {
                expect(typeof modifiedMessages[0].content).toBe("string");
            }
        });
        it("should not process regular text as image", () => {
            const originalMessages = [];
            const modifiedMessages = [
                {
                    role: "user",
                    content: regularText,
                },
            ];
            const processor = detector.createProcessor();
            processor(originalMessages, modifiedMessages);
            expect(modifiedMessages[0].content).toBe(regularText);
        });
        it("should only process user messages for content", () => {
            const originalMessages = [];
            const modifiedMessages = [
                {
                    role: "assistant",
                    content: validPngBase64,
                },
                {
                    role: "system",
                    content: validPngBase64,
                },
            ];
            const processor = detector.createProcessor();
            processor(originalMessages, modifiedMessages);
            expect(modifiedMessages[0].content).toBe(validPngBase64);
            expect(modifiedMessages[1].content).toBe(validPngBase64);
        });
        it("should process tool messages with JSON string containing image_url", () => {
            const imageDataUrl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==";
            const toolResponseJson = JSON.stringify({
                type: "image_url",
                image_url: {
                    url: imageDataUrl,
                    detail: "auto",
                },
            });
            const originalMessages = [];
            const modifiedMessages = [
                {
                    role: "tool",
                    content: toolResponseJson,
                    tool_call_id: "call_123",
                },
            ];
            const processor = detector.createProcessor();
            processor(originalMessages, modifiedMessages);
            expect(Array.isArray(modifiedMessages[0].content)).toBe(true);
            const content = modifiedMessages[0].content;
            expect(content).toHaveLength(1);
            expect(content[0]).toEqual({
                type: "image_url",
                image_url: {
                    url: imageDataUrl,
                    detail: "auto",
                },
            });
        });
        it("should process tool messages with plain base64 string", () => {
            const validPngBase64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==";
            const originalMessages = [];
            const modifiedMessages = [
                {
                    role: "tool",
                    content: validPngBase64,
                    tool_call_id: "call_456",
                },
            ];
            const processor = detector.createProcessor();
            processor(originalMessages, modifiedMessages);
            if (Array.isArray(modifiedMessages[0].content)) {
                const content = modifiedMessages[0].content;
                expect(content[0].type).toBe("image_url");
            }
        });
        it("should not process tool messages with regular text", () => {
            const originalMessages = [];
            const modifiedMessages = [
                {
                    role: "tool",
                    content: "Tool completed successfully",
                    tool_call_id: "call_789",
                },
            ];
            const processor = detector.createProcessor();
            processor(originalMessages, modifiedMessages);
            expect(modifiedMessages[0].content).toBe("Tool completed successfully");
        });
        it("should use custom image detail setting", () => {
            detector.setImageDetail("high");
            const originalMessages = [];
            const modifiedMessages = [
                {
                    role: "user",
                    content: validPngBase64,
                },
            ];
            const processor = detector.createProcessor();
            processor(originalMessages, modifiedMessages);
            const content = modifiedMessages[0].content;
            expect(content[0].image_url.detail).toBe("high");
        });
    });
    describe("Array content processing", () => {
        const validPngBase64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==";
        it("should process text items in content array", () => {
            const originalMessages = [];
            const modifiedMessages = [
                {
                    role: "user",
                    content: [
                        { type: "text", text: "Here is an image:" },
                        { type: "text", text: validPngBase64 },
                        { type: "text", text: "And some more text" },
                    ],
                },
            ];
            const processor = detector.createProcessor();
            processor(originalMessages, modifiedMessages);
            const content = modifiedMessages[0].content;
            expect(content).toHaveLength(3);
            expect(content[0].type).toBe("text");
            expect(content[1].type).toBe("image_url");
            expect(content[2].type).toBe("text");
        });
        it("should preserve existing image_url items in array", () => {
            const originalMessages = [];
            const modifiedMessages = [
                {
                    role: "user",
                    content: [
                        { type: "text", text: "Some text" },
                        {
                            type: "image_url",
                            image_url: { url: "http://example.com/image.png" },
                        },
                    ],
                },
            ];
            const processor = detector.createProcessor();
            processor(originalMessages, modifiedMessages);
            const content = modifiedMessages[0].content;
            expect(content).toHaveLength(2);
            expect(content[0].type).toBe("text");
            expect(content[1].type).toBe("image_url");
            expect(content[1].image_url.url).toBe("http://example.com/image.png");
        });
        it("should handle empty content array", () => {
            const originalMessages = [];
            const modifiedMessages = [
                {
                    role: "user",
                    content: [],
                },
            ];
            const processor = detector.createProcessor();
            expect(() => processor(originalMessages, modifiedMessages)).not.toThrow();
            expect(Array.isArray(modifiedMessages[0].content)).toBe(true);
        });
    });
    describe("Tool call argument processing", () => {
        const validPngBase64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==";
        it("should process base64 images in tool call arguments", () => {
            const originalMessages = [];
            const modifiedMessages = [
                {
                    role: "assistant",
                    content: "Using a tool",
                    tool_calls: [
                        {
                            id: "call_123",
                            type: "function",
                            function: {
                                name: "analyze_image",
                                arguments: JSON.stringify({
                                    image: validPngBase64,
                                    description: "Test image",
                                }),
                            },
                        },
                    ],
                },
            ];
            const processor = detector.createProcessor();
            processor(originalMessages, modifiedMessages);
            const toolCall = modifiedMessages[0].tool_calls[0];
            const args = JSON.parse(toolCall.function.arguments);
            expect(args.image).toContain("[CONVERTED TO IMAGE:");
            expect(args.description).toBe("Test image");
        });
        it("should handle nested objects in tool call arguments", () => {
            const originalMessages = [];
            const modifiedMessages = [
                {
                    role: "assistant",
                    content: "Using a tool",
                    tool_calls: [
                        {
                            id: "call_123",
                            type: "function",
                            function: {
                                name: "complex_tool",
                                arguments: JSON.stringify({
                                    data: {
                                        images: [validPngBase64, "regular text"],
                                        metadata: {
                                            thumbnail: validPngBase64,
                                        },
                                    },
                                }),
                            },
                        },
                    ],
                },
            ];
            const processor = detector.createProcessor();
            processor(originalMessages, modifiedMessages);
            const toolCall = modifiedMessages[0].tool_calls[0];
            const args = JSON.parse(toolCall.function.arguments);
            expect(args.data.images[0]).toContain("[CONVERTED TO IMAGE:");
            expect(args.data.images[1]).toBe("regular text");
            expect(args.data.metadata.thumbnail).toContain("[CONVERTED TO IMAGE:");
        });
        it("should handle invalid JSON in tool call arguments", () => {
            const originalMessages = [];
            const modifiedMessages = [
                {
                    role: "assistant",
                    content: "Using a tool",
                    tool_calls: [
                        {
                            id: "call_123",
                            type: "function",
                            function: {
                                name: "tool_with_plain_text",
                                arguments: validPngBase64,
                            },
                        },
                    ],
                },
            ];
            const processor = detector.createProcessor();
            processor(originalMessages, modifiedMessages);
            const toolCall = modifiedMessages[0].tool_calls[0];
            expect(toolCall.function.arguments).toContain("[CONVERTED TO IMAGE:");
        });
        it("should handle messages without tool calls", () => {
            const originalMessages = [];
            const modifiedMessages = [
                {
                    role: "assistant",
                    content: "Just a regular message",
                },
            ];
            const processor = detector.createProcessor();
            expect(() => processor(originalMessages, modifiedMessages)).not.toThrow();
        });
    });
    describe("Edge cases and error handling", () => {
        it("should handle empty messages array", () => {
            const originalMessages = [];
            const modifiedMessages = [];
            const processor = detector.createProcessor();
            expect(() => processor(originalMessages, modifiedMessages)).not.toThrow();
        });
        it("should handle null and undefined content", () => {
            const originalMessages = [];
            const modifiedMessages = [
                {
                    role: "user",
                    content: null,
                },
                {
                    role: "user",
                    content: undefined,
                },
            ];
            const processor = detector.createProcessor();
            expect(() => processor(originalMessages, modifiedMessages)).not.toThrow();
        });
        it("should handle unsupported image formats", () => {
            detector.setSupportedFormats(["png"]);
            const originalMessages = [];
            const modifiedMessages = [
                {
                    role: "user",
                    content: "data:image/bmp;base64,Qk1GAAAAAAAAADYAAAAoAAAAAQAAAAEAAAABACAAAAAAAAAAAAATCwAAEwsAAAAAAAAAAAAA/////wA=",
                },
            ];
            const processor = detector.createProcessor();
            processor(originalMessages, modifiedMessages);
            expect(typeof modifiedMessages[0].content).toBe("string");
        });
        it("should handle short base64 strings", () => {
            const originalMessages = [];
            const modifiedMessages = [
                {
                    role: "user",
                    content: "SGVsbG8=",
                },
            ];
            const processor = detector.createProcessor();
            processor(originalMessages, modifiedMessages);
            expect(modifiedMessages[0].content).toBe("SGVsbG8=");
        });
        it("should handle malformed data URLs", () => {
            const originalMessages = [];
            const modifiedMessages = [
                {
                    role: "user",
                    content: "data:image/png;base64",
                },
            ];
            const processor = detector.createProcessor();
            processor(originalMessages, modifiedMessages);
            expect(modifiedMessages[0].content).toBe("data:image/png;base64");
        });
    });
    describe("Global instance", () => {
        it("should provide global instance", () => {
            expect(Base64ImageDetector_1.globalBase64ImageDetector).toBeInstanceOf(Base64ImageDetector_1.Base64ImageProcessor);
        });
    });
    describe("loadImageAsBase64 tool", () => {
        let toolsService;
        let testImagePath;
        beforeEach(() => {
            toolsService = new Tools_1.ToolsService();
            detector.registerTool(toolsService);
            testImagePath = "/tmp/test-image.png";
            const pngBuffer = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==", "base64");
            fs.writeFileSync(testImagePath, pngBuffer);
        });
        afterEach(() => {
            if (fs.existsSync(testImagePath)) {
                fs.unlinkSync(testImagePath);
            }
        });
        it("should register loadImageAsBase64 tool", () => {
            const tools = toolsService.getTools();
            const loadImageTool = tools.find((t) => t.function.name === "loadImageAsBase64");
            expect(loadImageTool).toBeDefined();
            expect(loadImageTool?.function.name).toBe("loadImageAsBase64");
            expect(loadImageTool?.function.description).toContain("Load an image file");
        });
        it("should have function implementation", () => {
            const func = toolsService.getFunction("loadImageAsBase64");
            expect(func).toBeDefined();
            expect(typeof func).toBe("function");
        });
        it("should load image and return base64 data URL", async () => {
            const func = toolsService.getFunction("loadImageAsBase64");
            const result = await func(testImagePath);
            expect(typeof result).toBe("string");
            const parsed = JSON.parse(result);
            expect(parsed.type).toBe("image_url");
            expect(parsed.image_url.url).toContain("data:image/png;base64,");
            expect(parsed.image_url.detail).toBe("auto");
        });
        it("should accept custom detail parameter", async () => {
            const func = toolsService.getFunction("loadImageAsBase64");
            const result = await func(testImagePath, "high");
            const parsed = JSON.parse(result);
            expect(parsed.image_url.detail).toBe("high");
        });
        it("should throw error for non-existent file", async () => {
            const func = toolsService.getFunction("loadImageAsBase64");
            await expect(func("/path/to/nonexistent.png")).rejects.toThrow("File not found");
        });
        it("should throw error for unsupported format", async () => {
            const txtPath = "/tmp/test-file.txt";
            fs.writeFileSync(txtPath, "test content");
            const func = toolsService.getFunction("loadImageAsBase64");
            try {
                await expect(func(txtPath)).rejects.toThrow("Unsupported image format");
            }
            finally {
                fs.unlinkSync(txtPath);
            }
        });
        it("should throw error for directory path", async () => {
            const dirPath = "/tmp/test-dir";
            if (!fs.existsSync(dirPath)) {
                fs.mkdirSync(dirPath);
            }
            const func = toolsService.getFunction("loadImageAsBase64");
            try {
                await expect(func(dirPath)).rejects.toThrow("Path is not a file");
            }
            finally {
                fs.rmdirSync(dirPath);
            }
        });
    });
});
//# sourceMappingURL=Base64ImageDetector.test.js.map