"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.createFileStorageServer = createFileStorageServer;
const path = __importStar(require("path"));
const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
const zod_1 = require("zod");
const logger_1 = require("../../lib/logger");
const publish_1 = require("../../lib/events/publish");
const fileStorage = __importStar(require("../activities/file-storage"));
const MIME_MAP = {
    '.json': 'application/json', '.txt': 'text/plain', '.html': 'text/html',
    '.csv': 'text/csv', '.xml': 'application/xml', '.png': 'image/png',
    '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif',
    '.pdf': 'application/pdf', '.svg': 'image/svg+xml',
};
const writeFileSchema = zod_1.z.object({
    path: zod_1.z.string().describe('File path relative to storage root'),
    content: zod_1.z.string().describe('File content (text or base64-encoded binary)'),
    encoding: zod_1.z.enum(['utf-8', 'base64']).optional().default('utf-8')
        .describe('Content encoding'),
});
const readFileSchema = zod_1.z.object({
    path: zod_1.z.string().describe('File path relative to storage root'),
    encoding: zod_1.z.enum(['utf-8', 'base64']).optional().default('utf-8')
        .describe('Return encoding'),
});
const listFilesSchema = zod_1.z.object({
    directory: zod_1.z.string().optional().describe('Subdirectory to list (default: root)'),
    pattern: zod_1.z.string().optional().describe('Glob-like filter pattern (e.g., "*.json")'),
    page_size: zod_1.z.number().optional().describe('Max results per page (default 100)'),
    continuation_token: zod_1.z.string().optional().describe('Pagination token from a previous response'),
});
const deleteFileSchema = zod_1.z.object({
    path: zod_1.z.string().describe('File path relative to storage root'),
});
async function createFileStorageServer(options) {
    const name = options?.name || 'long-tail-file-storage';
    const instance = new mcp_js_1.McpServer({ name, version: '1.0.0' });
    instance.registerTool('write_file', {
        title: 'Write File',
        description: 'Write content to a file in storage. Creates directories as needed. Returns the storage reference and size.',
        inputSchema: writeFileSchema,
    }, async (args) => {
        const result = await fileStorage.writeFile(args);
        const ext = path.extname(args.path).toLowerCase();
        (0, publish_1.publishFileEvent)({
            type: 'file.stored',
            path: args.path,
            size: result.size,
            mime: MIME_MAP[ext] || 'application/octet-stream',
        });
        return { content: [{ type: 'text', text: JSON.stringify(result) }] };
    });
    instance.registerTool('read_file', {
        title: 'Read File',
        description: 'Read file content from storage. Returns content, size, and detected MIME type.',
        inputSchema: readFileSchema,
    }, async (args) => {
        try {
            const result = await fileStorage.readFile(args);
            return { content: [{ type: 'text', text: JSON.stringify(result) }] };
        }
        catch (err) {
            return { content: [{ type: 'text', text: JSON.stringify({ error: err.message }) }], isError: true };
        }
    });
    instance.registerTool('list_files', {
        title: 'List Files',
        description: 'List files and directories at a storage prefix. Supports cursor-based pagination via continuation tokens. Returns file paths, sizes, timestamps, subdirectories, and a nextToken for the next page.',
        inputSchema: listFilesSchema,
    }, async (args) => {
        const result = await fileStorage.listFiles(args);
        return { content: [{ type: 'text', text: JSON.stringify(result) }] };
    });
    instance.registerTool('delete_file', {
        title: 'Delete File',
        description: 'Remove a file from storage.',
        inputSchema: deleteFileSchema,
    }, async (args) => {
        const result = await fileStorage.deleteFile(args);
        if (result.deleted) {
            (0, publish_1.publishFileEvent)({ type: 'file.deleted', path: args.path });
        }
        return { content: [{ type: 'text', text: JSON.stringify(result) }] };
    });
    logger_1.loggerRegistry.info(`[lt-mcp:file-storage] ${name} ready (4 tools registered)`);
    return instance;
}
