"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 });
exports.loadRenderer = loadRenderer;
exports.loadRootModule = loadRootModule;
exports.loadChatModule = loadChatModule;
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const ConsoleRenderer_1 = require("./ConsoleRenderer");
const FancyRenderer_1 = require("./FancyRenderer");
const CompactRenderer_1 = require("./CompactRenderer");
const BUILTIN_RENDERERS = {
    basic: () => new ConsoleRenderer_1.ConsoleRenderer(),
    fancy: () => new FancyRenderer_1.FancyRenderer(),
    compact: () => new CompactRenderer_1.CompactRenderer(),
};
async function loadTsFile(filePath) {
    try {
        const jiti = require("jiti");
        const loader = typeof jiti === "function" ? jiti : jiti.default;
        return loader(filePath, { interopDefault: true })(filePath);
    }
    catch (_) { }
    try {
        require("ts-node/register");
        return require(filePath);
    }
    catch (_) { }
    try {
        const { register } = require("esbuild-register/dist/node");
        const { unregister } = register();
        const mod = require(filePath);
        unregister();
        return mod;
    }
    catch (_) { }
    throw new Error(`Cannot load TypeScript file "${filePath}". Install tsx, jiti, ts-node, or esbuild-register:\n` +
        `  npm install -g tsx\n  or  npm install -g ts-node`);
}
async function loadRenderer(specifier) {
    const builtin = BUILTIN_RENDERERS[specifier.toLowerCase()];
    if (builtin) {
        return builtin();
    }
    let mod;
    const isLocalPath = specifier.startsWith("./") ||
        specifier.startsWith("../") ||
        specifier.startsWith("/");
    if (isLocalPath) {
        const resolved = path_1.default.resolve(process.cwd(), specifier);
        if (!fs_1.default.existsSync(resolved)) {
            throw new Error(`Renderer file not found: ${resolved}`);
        }
        if (resolved.endsWith(".ts")) {
            mod = await loadTsFile(resolved);
        }
        else {
            mod = await Promise.resolve(`${resolved}`).then(s => __importStar(require(s)));
        }
    }
    else {
        try {
            mod = await Promise.resolve(`${specifier}`).then(s => __importStar(require(s)));
        }
        catch (err) {
            throw new Error(`Failed to load renderer package "${specifier}": ${err.message}\n` +
                `Make sure it is installed: npm install -g ${specifier}`);
        }
    }
    if (mod?.default && typeof mod.default.render === "function") {
        return mod.default;
    }
    if (typeof mod?.createRenderer === "function") {
        return mod.createRenderer();
    }
    if (mod?.renderer && typeof mod.renderer.render === "function") {
        return mod.renderer;
    }
    if (mod?.default && typeof mod.default === "function") {
        try {
            const instance = new mod.default();
            if (typeof instance.render === "function") {
                return instance;
            }
        }
        catch (_) { }
    }
    for (const key of Object.keys(mod || {})) {
        if (key.toLowerCase().includes("renderer") && typeof mod[key] === "function") {
            try {
                const instance = new mod[key]();
                if (typeof instance.render === "function") {
                    return instance;
                }
            }
            catch (_) { }
        }
    }
    throw new Error(`Renderer module "${specifier}" does not export a valid AgentRenderer.\n` +
        `Expected one of:\n` +
        `  - default export: AgentRenderer instance\n` +
        `  - default export: AgentRenderer class\n` +
        `  - named export "createRenderer": () => AgentRenderer\n` +
        `  - named export "renderer": AgentRenderer instance\n` +
        `  - named export "SomethingRenderer": AgentRenderer class`);
}
async function loadRootModule(specifier) {
    let mod;
    const isLocalPath = specifier.startsWith("./") ||
        specifier.startsWith("../") ||
        specifier.startsWith("/");
    if (isLocalPath) {
        const resolved = path_1.default.resolve(process.cwd(), specifier);
        if (!fs_1.default.existsSync(resolved)) {
            throw new Error(`Root module file not found: ${resolved}`);
        }
        if (resolved.endsWith(".ts")) {
            mod = await loadTsFile(resolved);
        }
        else {
            mod = await Promise.resolve(`${resolved}`).then(s => __importStar(require(s)));
        }
    }
    else {
        try {
            mod = await Promise.resolve(`${specifier}`).then(s => __importStar(require(s)));
        }
        catch (err) {
            throw new Error(`Failed to load root module package "${specifier}": ${err.message}`);
        }
    }
    if (mod?.default && typeof mod.default.initialize === "function") {
        return mod.default;
    }
    if (mod?.default && typeof mod.default === "function") {
        try {
            const instance = new mod.default();
            if (typeof instance.initialize === "function") {
                return instance;
            }
        }
        catch (_) { }
    }
    if (typeof mod?.createModule === "function") {
        return mod.createModule();
    }
    for (const key of Object.keys(mod || {})) {
        if (key.toLowerCase().includes("module") && typeof mod[key] === "function") {
            try {
                const instance = new mod[key]();
                if (typeof instance.initialize === "function") {
                    return instance;
                }
            }
            catch (_) { }
        }
    }
    throw new Error(`Root module "${specifier}" does not export a valid ChatModule.\n` +
        `Expected a class or instance with an "initialize(chatService)" method.`);
}
async function loadChatModule(specifier) {
    let mod;
    const isLocalPath = specifier.startsWith("./") ||
        specifier.startsWith("../") ||
        specifier.startsWith("/");
    if (isLocalPath) {
        const resolved = path_1.default.resolve(process.cwd(), specifier);
        if (!fs_1.default.existsSync(resolved)) {
            throw new Error(`Chat module file not found: ${resolved}`);
        }
        if (resolved.endsWith(".ts")) {
            mod = await loadTsFile(resolved);
        }
        else {
            mod = await Promise.resolve(`${resolved}`).then(s => __importStar(require(s)));
        }
    }
    else {
        try {
            mod = await Promise.resolve(`${specifier}`).then(s => __importStar(require(s)));
        }
        catch (err) {
            throw new Error(`Failed to load chat module package "${specifier}": ${err.message}`);
        }
    }
    if (mod?.default && typeof mod.default.initialize === "function") {
        return mod.default;
    }
    if (mod?.default && typeof mod.default === "function") {
        try {
            const instance = new mod.default();
            if (typeof instance.initialize === "function") {
                return instance;
            }
        }
        catch (_) { }
    }
    if (typeof mod?.createModule === "function") {
        return mod.createModule();
    }
    for (const key of Object.keys(mod || {})) {
        if (key.toLowerCase().includes("module") && typeof mod[key] === "function") {
            try {
                const instance = new mod[key]();
                if (typeof instance.initialize === "function") {
                    return instance;
                }
            }
            catch (_) { }
        }
    }
    throw new Error(`Chat module "${specifier}" does not export a valid ChatModule.\n` +
        `Expected a class or instance with an "initialize(chatService)" method.\n` +
        `Supported export patterns:\n` +
        `  - default export: ChatModule instance or class\n` +
        `  - named export "createModule": () => ChatModule\n` +
        `  - named export "SomethingModule": ChatModule class`);
}
//# sourceMappingURL=loadRenderer.js.map