"use strict";
// =============================================================================
// Pure Agent - Parse Document Tool
// Ported from server.js parse_document handler
// Parses PDF/DOCX/PPTX/XLSX files, extracts text and embedded media
// =============================================================================
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 fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const tool_registry_1 = require("../tool-registry");
const result_types_1 = require("../result-types");
// ---------------------------------------------------------------------------
// PDF parsing (using pdfjs-dist)
// ---------------------------------------------------------------------------
async function parsePdf(filePath) {
    const pdfjsLib = require('pdfjs-dist');
    pdfjsLib.GlobalWorkerOptions.workerSrc = '';
    const data = new Uint8Array(fs.readFileSync(filePath));
    const doc = await pdfjsLib.getDocument({ data }).promise;
    const pages = doc.numPages;
    const textParts = [];
    for (let i = 1; i <= pages; i++) {
        const page = await doc.getPage(i);
        const content = await page.getTextContent();
        const pageText = content.items.map((item) => item.str).join(' ');
        if (pageText.trim())
            textParts.push(`--- Page ${i} ---\n${pageText}`);
    }
    return { text: textParts.join('\n\n'), pages };
}
async function parseOfficeFile(filePath, ext) {
    const JSZip = require('jszip');
    const zip = await JSZip.loadAsync(fs.readFileSync(filePath));
    // Config per format
    const config = {
        docx: { textFiles: ['word/document.xml'], mediaDir: 'word/media/' },
        pptx: { textFiles: ['ppt/slides/slide*.xml'], mediaDir: 'ppt/media/' },
        xlsx: { textFiles: ['xl/sharedStrings.xml'], mediaDir: 'xl/media/' },
    };
    const cfg = config[ext] || config.docx;
    const images = [];
    const media = [];
    const SUPPORTED_IMG = new Set(['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp']);
    const VIDEO_EXTS = new Set(['mp4', 'mov', 'avi', 'wmv', 'webm']);
    const AUDIO_EXTS = new Set(['mp3', 'wav', 'm4a', 'ogg', 'aac']);
    // Extract media files
    for (const [filename, file] of Object.entries(zip.files)) {
        if (!filename.startsWith(cfg.mediaDir))
            continue;
        const mediaName = path.basename(filename);
        const mediaExt = path.extname(mediaName).toLowerCase().replace('.', '');
        if (SUPPORTED_IMG.has(mediaExt)) {
            const data = await file.async('base64');
            const mimeMap = {
                png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',
                gif: 'image/gif', bmp: 'image/bmp', webp: 'image/webp',
            };
            images.push({ name: mediaName, base64: data, mime: mimeMap[mediaExt] || 'image/jpeg' });
        }
        else if (VIDEO_EXTS.has(mediaExt) || AUDIO_EXTS.has(mediaExt)) {
            const data = await file.async('nodebuffer');
            media.push({ name: mediaName, type: VIDEO_EXTS.has(mediaExt) ? 'video' : 'audio' });
        }
    }
    // Extract text
    const textParts = [];
    for (const pattern of cfg.textFiles) {
        if (pattern.includes('*')) {
            // Glob-like matching
            const prefix = pattern.split('*')[0];
            const suffix = pattern.split('*')[1] || '';
            for (const [filename, file] of Object.entries(zip.files)) {
                if (filename.startsWith(prefix) && filename.endsWith(suffix)) {
                    const xml = await file.async('string');
                    let text = xml.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
                    if (ext === 'pptx') {
                        const slideNum = filename.match(/slide(\d+)/)?.[1] || '?';
                        textParts.push(`--- Slide ${slideNum} ---\n${text}`);
                    }
                    else {
                        textParts.push(text);
                    }
                }
            }
        }
        else {
            const file = zip.files[pattern];
            if (file) {
                const xml = await file.async('string');
                let text = xml;
                if (ext === 'docx') {
                    text = text.replace(/<\/w:p>/g, '\n').replace(/<\/w:tr>/g, '\n');
                }
                text = text.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
                textParts.push(text);
            }
        }
    }
    return {
        text: textParts.join(ext === 'pptx' ? '\n\n' : '\n'),
        images,
        media,
    };
}
// ---------------------------------------------------------------------------
// Handler
// ---------------------------------------------------------------------------
async function parseDocumentHandler(args, context) {
    const { path: filepath } = args;
    if (!filepath)
        return (0, result_types_1.toolError)('Missing required parameter: path');
    const resolved = path.resolve(filepath);
    if (!fs.existsSync(resolved)) {
        return (0, result_types_1.toolError)(`File not found: ${resolved}`);
    }
    const ext = path.extname(resolved).toLowerCase().replace('.', '');
    const baseName = path.basename(resolved);
    try {
        if (ext === 'pdf') {
            const result = await parsePdf(resolved);
            return (0, result_types_1.toolResult)({
                success: true,
                filename: baseName,
                text: result.text,
                pages: result.pages,
                images: [],
                media: [],
            });
        }
        if (['docx', 'pptx', 'xlsx'].includes(ext)) {
            const result = await parseOfficeFile(resolved, ext);
            return (0, result_types_1.toolResult)({
                success: true,
                filename: baseName,
                text: result.text,
                images: result.images.length > 0
                    ? result.images.map(img => ({
                        name: img.name,
                        base64_data: img.base64,
                        mime: img.mime,
                    }))
                    : undefined,
                media: result.media.length > 0 ? result.media : undefined,
            });
        }
        return (0, result_types_1.toolError)(`Unsupported file format: .${ext}. Supported: PDF, DOCX, PPTX, XLSX`);
    }
    catch (err) {
        return (0, result_types_1.toolError)(`Failed to parse document: ${err.message}`);
    }
}
// ---------------------------------------------------------------------------
// Registration
// ---------------------------------------------------------------------------
tool_registry_1.registry.register({
    name: 'parse_document',
    toolset: 'file',
    schema: {
        description: 'Parse document files (PDF/DOCX/PPTX/XLSX). Extracts text content and embedded images. Returns text and images for the model to analyze.',
        parameters: {
            type: 'object',
            properties: {
                path: {
                    type: 'string',
                    description: 'Path to the document file (absolute or relative)',
                },
            },
            required: ['path'],
        },
    },
    handler: parseDocumentHandler,
    isAsync: true,
    description: 'Parse PDF/DOCX/PPTX/XLSX documents',
    emoji: '📄',
    maxResultSizeChars: 200000,
});
//# sourceMappingURL=parse-document.js.map