"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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
jest.mock("../../../src/utils", () => ({
    readFile: jest.fn(),
    fileExists: jest.fn().mockReturnValue(true),
    fileStat: jest.fn(),
}));
jest.mock("../../../src/config", () => ({
    getConfig: jest.fn(),
    getLanguageConfig: jest.fn(),
    updateLanguageConfig: jest.fn(),
}));
jest.mock("../../../src/plugins/plugins", () => ({
    PluginService: jest.fn().mockImplementation(() => ({
        listPlugins: jest.fn().mockReturnValue([]),
        call: jest.fn().mockResolvedValue([]),
    })),
}));
const language_1 = require("../../../src/plugins/language");
const config_1 = require("../../../src/config");
const plugins_1 = require("../../../src/plugins/plugins");
const utils = __importStar(require("../../../src/utils"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const os_1 = require("os");
describe("LanguagePlugin - Integration Tests", () => {
    let plugin;
    let tempDir;
    let tempFile;
    let mockEventService;
    let mockPluginService;
    beforeEach(async () => {
        tempDir = path_1.default.join((0, os_1.tmpdir)(), "languageplugin-test-" + Date.now());
        fs_1.default.mkdirSync(tempDir, { recursive: true });
        tempFile = path_1.default.join(tempDir, "test-file.ts");
        mockEventService = {
            on: jest.fn(),
            emit: jest.fn(),
        };
        mockPluginService = new plugins_1.PluginService({});
        mockPluginService.listPlugins = jest.fn().mockReturnValue([]);
        mockPluginService.call = jest.fn().mockResolvedValue([]);
        config_1.getConfig.mockResolvedValue({
            plugins: { enabled: [], disabled: [] },
        });
        config_1.getLanguageConfig.mockResolvedValue({
            "test(": {
                events: ["file:post-read", "file:post-edit"],
                sources: [
                    {
                        kind: "text",
                        data: ["Testing context: This is test-related information"],
                    },
                ],
            },
        });
        utils.readFile.mockImplementation((filePath) => {
            if (fs_1.default.existsSync(filePath)) {
                return Promise.resolve(fs_1.default.readFileSync(filePath));
            }
            return Promise.reject(new Error("File not found"));
        });
        plugin = new language_1.LanguagePlugin({
            Events: mockEventService,
            Plugins: mockPluginService,
        });
    });
    afterEach(() => {
        if (fs_1.default.existsSync(tempFile)) {
            fs_1.default.unlinkSync(tempFile);
        }
        if (fs_1.default.existsSync(tempDir)) {
            fs_1.default.rmdirSync(tempDir);
        }
    });
    test("should trigger when reading real files with test content", async () => {
        const testContent = `
function calculateSum(a: number, b: number): number {
  return a + b;
}

test("should calculate sum correctly", () => {
  expect(calculateSum(2, 3)).toBe(5);
});
`;
        fs_1.default.writeFileSync(tempFile, testContent);
        const eventHandlers = new Map();
        mockEventService.on.mockImplementation((event, handler) => {
            eventHandlers.set(event, handler);
        });
        plugin = new language_1.LanguagePlugin({
            Events: mockEventService,
            Plugins: mockPluginService,
        });
        await new Promise((resolve) => setTimeout(resolve, 10));
        const fileReadHandler = eventHandlers.get("file:post-read");
        if (fileReadHandler) {
            await fileReadHandler({
                filePath: tempFile,
                fileContent: fs_1.default.readFileSync(tempFile),
            });
        }
        await new Promise((resolve) => setTimeout(resolve, 10));
        expect(mockEventService.emit).toHaveBeenCalledWith("agent:msg", expect.stringMatching(/<Workflow>[\s\S]*language_context_trigger[\s\S]*<\/Workflow>/));
    });
    test("should work with readFile tool simulation", async () => {
        const testContent = `
import { describe, it, expect } from 'vitest';

describe('User service', () => {
  it('should create user', async () => {
    const user = await createUser({ name: 'John' });
    expect(user.id).toBeDefined();
  });

  test('should validate email', () => {
    expect(isValidEmail('test@example.com')).toBe(true);
  });
});
`;
        fs_1.default.writeFileSync(tempFile, testContent);
        const eventHandlers = new Map();
        mockEventService.on.mockImplementation((event, handler) => {
            eventHandlers.set(event, handler);
        });
        plugin = new language_1.LanguagePlugin({
            Events: mockEventService,
            Plugins: mockPluginService,
        });
        await new Promise((resolve) => setTimeout(resolve, 10));
        const fileReadHandler = eventHandlers.get("file:post-read");
        if (fileReadHandler) {
            await fileReadHandler({
                filePath: tempFile,
                fileContent: fs_1.default.readFileSync(tempFile),
            });
        }
        await new Promise((resolve) => setTimeout(resolve, 10));
        expect(mockEventService.emit).toHaveBeenCalledWith("agent:msg", expect.stringMatching(/<Workflow>[\s\S]*Testing context[\s\S]*<\/Workflow>/));
    });
    test("should work with file editing scenarios", async () => {
        const initialContent = `
function getUserData(id: string) {
  return database.find(id);
}
`;
        fs_1.default.writeFileSync(tempFile, initialContent);
        const eventHandlers = new Map();
        mockEventService.on.mockImplementation((event, handler) => {
            eventHandlers.set(event, handler);
        });
        plugin = new language_1.LanguagePlugin({
            Events: mockEventService,
            Plugins: mockPluginService,
        });
        await new Promise((resolve) => setTimeout(resolve, 10));
        const fileReadHandler = eventHandlers.get("file:post-read");
        if (fileReadHandler) {
            await fileReadHandler({
                filePath: tempFile,
                fileContent: fs_1.default.readFileSync(tempFile),
            });
        }
        await new Promise((resolve) => setTimeout(resolve, 10));
        expect(mockEventService.emit).not.toHaveBeenCalled();
        const editedContent = initialContent +
            `

test('should get user data', () => {
  const result = getUserData('123');
  expect(result).toBeDefined();
});
`;
        fs_1.default.writeFileSync(tempFile, editedContent);
        mockEventService.emit.mockClear();
        const fileEditHandler = eventHandlers.get("file:post-edit");
        if (fileEditHandler) {
            await fileEditHandler({
                filePath: tempFile,
                fileContent: fs_1.default.readFileSync(tempFile),
            });
        }
        await new Promise((resolve) => setTimeout(resolve, 10));
        expect(mockEventService.emit).toHaveBeenCalledWith("agent:msg", expect.stringMatching(/<Workflow>[\s\S]*Testing context[\s\S]*<\/Workflow>/));
    });
    test("should handle multiple language terms in same file", async () => {
        config_1.getLanguageConfig.mockResolvedValue({
            "test(": {
                events: ["file:post-read"],
                sources: [
                    {
                        kind: "text",
                        data: ["Testing context: This is test-related information"],
                    },
                ],
            },
            database: {
                events: ["file:post-read"],
                sources: [
                    {
                        kind: "text",
                        data: ["Database context: Connection and query information"],
                    },
                ],
            },
        });
        const testContent = `
import { database } from './db';

test('should query database correctly', async () => {
  const result = await database.query('SELECT * FROM users');
  expect(result.length).toBeGreaterThan(0);
});
`;
        fs_1.default.writeFileSync(tempFile, testContent);
        const eventHandlers = new Map();
        mockEventService.on.mockImplementation((event, handler) => {
            eventHandlers.set(event, handler);
        });
        plugin = new language_1.LanguagePlugin({
            Events: mockEventService,
            Plugins: mockPluginService,
        });
        await new Promise((resolve) => setTimeout(resolve, 10));
        const fileReadHandler = eventHandlers.get("file:post-read");
        if (fileReadHandler) {
            await fileReadHandler({
                filePath: tempFile,
                fileContent: fs_1.default.readFileSync(tempFile),
            });
        }
        await new Promise((resolve) => setTimeout(resolve, 10));
        expect(mockEventService.emit).toHaveBeenCalledWith("agent:msg", expect.stringMatching(/<Workflow>[\s\S]*language_context_trigger[\s\S]*<\/Workflow>/));
        const emitCalls = mockEventService.emit.mock.calls.filter((call) => call[0] === "agent:msg");
        expect(emitCalls.length).toBeGreaterThan(0);
        const workflowContent = emitCalls[0][1].match(/<Workflow>\s*(\{[\s\S]*?\})\s*<\/Workflow>/);
        expect(workflowContent).toBeDefined();
        const eventData = JSON.parse(workflowContent[1]);
        expect(eventData.matchingTerms).toEqual(expect.arrayContaining(["test(", "database"]));
    });
    test("should work with different file extensions", async () => {
        const jsFile = path_1.default.join(tempDir, "test-file.js");
        const jsContent = `
function sum(a, b) {
  return a + b;
}

test('sum function works', () => {
  expect(sum(1, 2)).toBe(3);
});
`;
        fs_1.default.writeFileSync(jsFile, jsContent);
        const eventHandlers = new Map();
        mockEventService.on.mockImplementation((event, handler) => {
            eventHandlers.set(event, handler);
        });
        plugin = new language_1.LanguagePlugin({
            Events: mockEventService,
            Plugins: mockPluginService,
        });
        await new Promise((resolve) => setTimeout(resolve, 10));
        const fileReadHandler = eventHandlers.get("file:post-read");
        if (fileReadHandler) {
            await fileReadHandler({
                filePath: jsFile,
                fileContent: fs_1.default.readFileSync(jsFile),
            });
        }
        await new Promise((resolve) => setTimeout(resolve, 10));
        expect(mockEventService.emit).toHaveBeenCalledWith("agent:msg", expect.stringMatching(/<Workflow>[\s\S]*Testing context[\s\S]*<\/Workflow>/));
        fs_1.default.unlinkSync(jsFile);
    });
    test("should handle large files efficiently", async () => {
        let largeContent = "// Large file for performance testing\n";
        for (let i = 0; i < 1000; i++) {
            largeContent += `function helper${i}() { return ${i}; }\n`;
        }
        largeContent += `
test('performance test', () => {
  expect(helper999()).toBe(999);
});
`;
        fs_1.default.writeFileSync(tempFile, largeContent);
        const eventHandlers = new Map();
        mockEventService.on.mockImplementation((event, handler) => {
            eventHandlers.set(event, handler);
        });
        plugin = new language_1.LanguagePlugin({
            Events: mockEventService,
            Plugins: mockPluginService,
        });
        await new Promise((resolve) => setTimeout(resolve, 10));
        const startTime = Date.now();
        const fileReadHandler = eventHandlers.get("file:post-read");
        if (fileReadHandler) {
            await fileReadHandler({
                filePath: tempFile,
                fileContent: fs_1.default.readFileSync(tempFile),
            });
        }
        await new Promise((resolve) => setTimeout(resolve, 50));
        const processingTime = Date.now() - startTime;
        expect(mockEventService.emit).toHaveBeenCalledWith("agent:msg", expect.stringMatching(/<Workflow>[\s\S]*Testing context[\s\S]*<\/Workflow>/));
        expect(processingTime).toBeLessThan(1000);
    });
});
//# sourceMappingURL=languagePlugin-integration.test.js.map