"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.createTranslationServer = createTranslationServer;
exports.stopTranslationServer = stopTranslationServer;
const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
const zod_1 = require("zod");
const llm_1 = require("../../services/llm");
const defaults_1 = require("../../modules/defaults");
const logger_1 = require("../../lib/logger");
function TRANSLATE_SYSTEM_PROMPT(targetLanguage) {
    return `You are a translation assistant. Translate the user's text to ${targetLanguage}. Return ONLY a JSON object: {"translated_content": "...", "source_language": "detected ISO code"}. No markdown, no explanation.`;
}
const translateContentSchema = zod_1.z.object({
    content: zod_1.z.string().describe('The content text to translate'),
    target_language: zod_1.z.string().describe('Target language code (e.g. "en", "es")'),
    source_language: zod_1.z.string().optional().describe('Source language code (auto-detected if omitted)'),
});
function registerTools(srv) {
    srv.registerTool('translate_content', {
        title: 'Translate Content',
        description: 'Translate content text to the target language. Returns the translated content and detected source language.',
        inputSchema: translateContentSchema,
    }, async (args) => {
        const { hasLLMApiKey } = await Promise.resolve().then(() => __importStar(require('../../services/llm')));
        if (!hasLLMApiKey(defaults_1.LLM_MODEL_SECONDARY)) {
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify({
                            translated_content: args.content,
                            source_language: args.source_language || 'unknown',
                            target_language: args.target_language,
                            note: 'LLM API key not configured — returned content unchanged',
                        }),
                    }],
            };
        }
        const systemPrompt = args.source_language
            ? `You are a translation assistant. Translate the user's text from ${args.source_language} to ${args.target_language}. Return ONLY a JSON object: {"translated_content": "...", "source_language": "${args.source_language}"}. No markdown, no explanation.`
            : TRANSLATE_SYSTEM_PROMPT(args.target_language);
        const response = await (0, llm_1.callLLM)({
            model: defaults_1.LLM_MODEL_SECONDARY,
            messages: [
                { role: 'system', content: systemPrompt },
                { role: 'user', content: args.content },
            ],
            max_tokens: defaults_1.LLM_MAX_TOKENS_VISION,
            temperature: 0,
        });
        const raw = response.content || '';
        try {
            const cleaned = raw.replace(/^```json\n?|\n?```$/g, '').trim();
            const parsed = JSON.parse(cleaned);
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify({
                            translated_content: parsed.translated_content || args.content,
                            source_language: parsed.source_language || args.source_language || 'unknown',
                            target_language: args.target_language,
                        }),
                    }],
            };
        }
        catch {
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify({
                            translated_content: raw,
                            source_language: args.source_language || 'unknown',
                            target_language: args.target_language,
                        }),
                    }],
            };
        }
    });
}
/**
 * Create the Translation MCP server.
 *
 * Returns a fresh McpServer instance each time. The MCP SDK only allows
 * one transport per server, so each consumer needs its own instance.
 */
async function createTranslationServer(options) {
    const name = options?.name || 'long-tail-translation';
    const instance = new mcp_js_1.McpServer({ name, version: '1.0.0' });
    registerTools(instance);
    logger_1.loggerRegistry.info(`[lt-mcp:translation] ${name} ready (1 tool registered)`);
    return instance;
}
/**
 * Stop a Translation MCP server instance.
 */
async function stopTranslationServer() {
    logger_1.loggerRegistry.info('[lt-mcp:translation] stopped');
}
