"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 language_1 = require("../../../src/plugins/language");
const utils = __importStar(require("../../../src/utils"));
const config_1 = require("../../../src/config");
jest.mock("../../../src/utils", () => ({
    readFile: jest.fn(),
    fileExists: jest.fn().mockReturnValue(true),
    fileStat: jest.fn().mockResolvedValue({
        isDirectory: jest.fn().mockReturnValue(false),
        isFile: jest.fn().mockReturnValue(true),
        size: 1024,
    }),
}));
jest.mock("../../../src/services/EventService", () => ({
    EventService: jest.fn().mockImplementation(() => ({
        on: jest.fn(),
        emit: jest.fn(),
        log: jest.fn(),
    })),
}));
jest.mock("../../../src/config", () => ({
    getConfig: jest.fn(),
    getConfigSync: jest.fn(),
    getLanguageConfig: jest.fn(),
}));
jest.mock("../../../src/plugins/plugins", () => ({
    PluginService: jest.fn().mockImplementation(() => ({
        listPlugins: jest.fn(),
        call: jest.fn(),
    })),
}));
const mockedConfig = config_1.getConfig;
const mockedLanguageConfig = config_1.getLanguageConfig;
const mockedReadFile = utils.readFile;
describe("LanguagePlugin - Content-Based Triggering", () => {
    let mockEventService;
    let mockPluginService;
    let eventHandlers;
    beforeEach(() => {
        eventHandlers = new Map();
        mockEventService = {
            on: jest.fn((event, handler) => {
                eventHandlers.set(event, handler);
            }),
            emit: jest.fn(),
            log: jest.fn(),
        };
        mockPluginService = {
            listPlugins: jest.fn().mockReturnValue(["github"]),
            call: jest.fn().mockResolvedValue(["plugin context data"]),
        };
        jest.clearAllMocks();
    });
    test("should trigger on file content containing test functions", async () => {
        const fileContentWithTests = `
      import { expect } from 'jest';

      describe('MyComponent', () => {
        test('should render correctly', () => {
          expect(component).toBeTruthy();
        });

        it('should handle click events', () => {
          // test implementation
        });
      });
    `;
        mockedReadFile.mockResolvedValue(Buffer.from(fileContentWithTests));
        mockedConfig.mockResolvedValue({
            plugins: { enabled: [], disabled: [] },
            modules: [],
            promptsDir: ".knowhow/prompts",
            sources: [],
            embedSources: [],
            embeddingModel: "text-embedding-ada-002",
            agents: [],
            mcps: [],
            modelProviders: [],
        });
        mockedLanguageConfig.mockResolvedValue({
            "test(": {
                events: ["file:post-read"],
                sources: [
                    { kind: "text", data: ["Jest testing best practices"] },
                    { kind: "file", data: ["docs/testing-guidelines.md"] },
                ],
            },
        });
        new language_1.LanguagePlugin({
            Events: mockEventService,
            Plugins: mockPluginService,
        });
        await new Promise((resolve) => setTimeout(resolve, 0));
        const fileReadHandler = eventHandlers.get("file:post-read");
        expect(fileReadHandler).toBeDefined();
        await fileReadHandler({
            filePath: "src/components/MyComponent.spec.ts",
            operation: "read",
        });
        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 emitCall = mockEventService.emit.mock.calls.find((call) => call[0] === "agent:msg");
        expect(emitCall).toBeDefined();
        const workflowContent = emitCall[1].match(/<Workflow>\s*(\{[\s\S]*?\})\s*<\/Workflow>/);
        expect(workflowContent).toBeDefined();
        const eventData = JSON.parse(workflowContent[1]);
        expect(eventData.type).toBe("language_context_trigger");
        expect(eventData.matchingTerms).toContain("test(");
        expect(eventData.contextMessage).toContain("Jest testing best practices");
    });
    test("should not trigger when file content doesn't match", async () => {
        const fileContent = `
      const config = {
        database: 'postgresql',
        port: 5432
      };
    `;
        mockedReadFile.mockResolvedValue(Buffer.from(fileContent));
        mockedConfig.mockResolvedValue({
            plugins: { enabled: [], disabled: [] },
            modules: [],
            promptsDir: ".knowhow/prompts",
            sources: [],
            embedSources: [],
            embeddingModel: "text-embedding-ada-002",
            agents: [],
            mcps: [],
            modelProviders: [],
        });
        mockedLanguageConfig.mockResolvedValue({
            "test(": {
                events: ["file:post-read"],
                sources: [{ kind: "text", data: ["Jest testing best practices"] }],
            },
        });
        new language_1.LanguagePlugin({
            Events: mockEventService,
            Plugins: mockPluginService,
        });
        await new Promise((resolve) => setTimeout(resolve, 0));
        const fileReadHandler = eventHandlers.get("file:post-read");
        expect(fileReadHandler).toBeDefined();
        await fileReadHandler({
            filePath: "src/config.js",
            operation: "read",
        });
        await new Promise((resolve) => setTimeout(resolve, 10));
        expect(mockEventService.emit).not.toHaveBeenCalled();
    });
    test("should handle file read errors gracefully", async () => {
        mockedReadFile.mockRejectedValue(new Error("File not found"));
        mockedConfig.mockResolvedValue({
            plugins: { enabled: [], disabled: [] },
            modules: [],
            promptsDir: ".knowhow/prompts",
            sources: [],
            embedSources: [],
            embeddingModel: "text-embedding-ada-002",
            agents: [],
            mcps: [],
            modelProviders: [],
        });
        mockedLanguageConfig.mockResolvedValue({
            "test(": {
                events: ["file:post-read"],
                sources: [{ kind: "text", data: ["Jest testing best practices"] }],
            },
        });
        new language_1.LanguagePlugin({
            Events: mockEventService,
            Plugins: mockPluginService,
        });
        await new Promise((resolve) => setTimeout(resolve, 0));
        const fileReadHandler = eventHandlers.get("file:post-read");
        expect(fileReadHandler).toBeDefined();
        await fileReadHandler({
            filePath: "src/nonexistent.test.js",
            operation: "read",
        });
        await new Promise((resolve) => setTimeout(resolve, 10));
        expect(mockEventService.emit).not.toHaveBeenCalled();
    });
    test("should work with case-insensitive matching", async () => {
        const fileContent = `
      function myTEST() {
        return true;
      }
    `;
        mockedReadFile.mockResolvedValue(Buffer.from(fileContent));
        mockedConfig.mockResolvedValue({
            plugins: { enabled: [], disabled: [] },
            modules: [],
            promptsDir: ".knowhow/prompts",
            sources: [],
            embedSources: [],
            embeddingModel: "text-embedding-ada-002",
            agents: [],
            mcps: [],
            modelProviders: [],
        });
        mockedLanguageConfig.mockResolvedValue({
            "test(": {
                events: ["file:post-read"],
                sources: [{ kind: "text", data: ["Jest testing best practices"] }],
            },
        });
        new language_1.LanguagePlugin({
            Events: mockEventService,
            Plugins: mockPluginService,
        });
        await new Promise((resolve) => setTimeout(resolve, 0));
        const fileReadHandler = eventHandlers.get("file:post-read");
        expect(fileReadHandler).toBeDefined();
        await fileReadHandler({
            filePath: "src/utils.js",
            operation: "read",
        });
        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 trigger on file:post-edit events", async () => {
        const fileContent = `
      test('new test case', () => {
        expect(true).toBe(true);
      });
    `;
        mockedReadFile.mockResolvedValue(Buffer.from(fileContent));
        mockedConfig.mockResolvedValue({
            plugins: { enabled: [], disabled: [] },
            modules: [],
            promptsDir: ".knowhow/prompts",
            sources: [],
            embedSources: [],
            embeddingModel: "text-embedding-ada-002",
            agents: [],
            mcps: [],
            modelProviders: [],
        });
        mockedLanguageConfig.mockResolvedValue({
            "test(": {
                events: ["file:post-read", "file:post-edit"],
                sources: [{ kind: "text", data: ["Jest testing best practices"] }],
            },
        });
        new language_1.LanguagePlugin({
            Events: mockEventService,
            Plugins: mockPluginService,
        });
        await new Promise((resolve) => setTimeout(resolve, 0));
        const fileEditHandler = eventHandlers.get("file:post-edit");
        expect(fileEditHandler).toBeDefined();
        await fileEditHandler({
            filePath: "src/newFeature.test.js",
            operation: "edit",
        });
        await new Promise((resolve) => setTimeout(resolve, 10));
        expect(mockEventService.emit).toHaveBeenCalledWith("agent:msg", expect.stringMatching(/<Workflow>[\s\S]*language_context_trigger[\s\S]*<\/Workflow>/));
    });
});
//# sourceMappingURL=languagePlugin-content-triggers.test.js.map