"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 });
exports.ModulesService = void 0;
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const config_1 = require("../../config");
const __1 = require("../");
const utils_1 = require("../../utils");
class ModulesService {
    async getDefaultContext() {
        return { ...(0, __1.services)() };
    }
    async overrideDefaultContext(overrides) {
        const defaultContext = await this.getDefaultContext();
        return { ...defaultContext, ...overrides };
    }
    async loadModulesFrom(config, context) {
        if (!context) {
            context = { ...(await this.getDefaultContext()) };
        }
        const allModulePaths = config.modules;
        const resolvePaths = [
            path.join(process.cwd(), ".knowhow", "node_modules"),
            path.join(os.homedir(), ".knowhow", "node_modules"),
            path.join(process.cwd(), "node_modules"),
        ];
        for (const modulePath of allModulePaths) {
            let resolvedPath;
            if (modulePath.startsWith(".")) {
                resolvedPath = path.resolve(process.cwd(), modulePath);
            }
            else {
                try {
                    resolvedPath = require.resolve(modulePath, { paths: resolvePaths });
                }
                catch {
                    resolvedPath = modulePath;
                }
            }
            let importedModule;
            try {
                const rawModule = require(resolvedPath);
                importedModule = (rawModule.default || rawModule);
                context.Events?.log("ModulesService", `🔌 Loading module: ${modulePath} (resolved: ${resolvedPath})`);
                await importedModule.init({
                    config,
                    cwd: process.cwd(),
                    context: context,
                });
                context.Events?.log("ModulesService", `✅ Module initialized: ${modulePath} (tools: ${importedModule.tools.length}, agents: ${importedModule.agents.length}, plugins: ${importedModule.plugins.length}, clients: ${importedModule.clients.length})`);
            }
            catch (err) {
                process.stderr.write(`\n⚠️  Failed to load module "${modulePath}": ${err.message}\n` +
                    `   Run "knowhow modules setup --global" or "knowhow modules install ${modulePath} --global" to fix this.\n\n`);
                continue;
            }
            if (context.Agents) {
                for (const agent of importedModule.agents) {
                    context.Agents.registerAgent(agent);
                }
            }
            if (context.Tools) {
                for (const tool of importedModule.tools) {
                    context.Tools.addTool(tool.definition);
                    context.Tools.setFunction(tool.definition.function.name, tool.handler);
                }
            }
            if (context.Plugins) {
                for (const plugin of importedModule.plugins) {
                    context.Plugins.registerPlugin(plugin.name, new plugin.plugin(context));
                }
            }
            if (context.Clients) {
                for (const client of importedModule.clients) {
                    context.Clients.registerClient(client.provider, client.client);
                    context.Clients.registerModels(client.provider, client.models);
                }
            }
        }
    }
    async loadModulesFromConfig(context) {
        const config = await (0, config_1.getConfig)();
        const globalConfig = await (0, config_1.getGlobalConfig)();
        const allModulePaths = [
            ...(globalConfig.modules || []),
            ...(config.modules || []),
        ];
        return this.loadModulesFrom({ ...config, modules: (0, utils_1.toUniqueArray)(allModulePaths) }, context);
    }
}
exports.ModulesService = ModulesService;
//# sourceMappingURL=index.js.map