"use strict";
// =============================================================================
// Pure Agent - Conversation Files Manager
// Manages per-conversation file storage for multimodal content
// Saves base64 media to disk, stores references in messages
// =============================================================================
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.ensureConvDir = ensureConvDir;
exports.saveMediaFile = saveMediaFile;
exports.saveTextFile = saveTextFile;
exports.extractAndSaveMedia = extractAndSaveMedia;
exports.loadMediaAsBase64 = loadMediaAsBase64;
exports.resolveMediaUrl = resolveMediaUrl;
exports.cleanupConvFiles = cleanupConvFiles;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const constants_1 = require("./constants");
const logger_1 = require("./logger");
// ---------------------------------------------------------------------------
// Directory management
// ---------------------------------------------------------------------------
function getConvFilesDir() {
    return path.join((0, constants_1.getPureAgentHome)(), 'conv-files');
}
function getConvDir(convId) {
    return path.join(getConvFilesDir(), convId);
}
function ensureConvDir(convId) {
    const dir = getConvDir(convId);
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
    }
    return dir;
}
// ---------------------------------------------------------------------------
// Save media file from base64
// ---------------------------------------------------------------------------
function saveMediaFile(convId, base64Data, mimeType, prefix = 'media') {
    const dir = ensureConvDir(convId);
    // Determine extension from MIME type
    const extMap = {
        'image/png': '.png', 'image/jpeg': '.jpg', 'image/gif': '.gif',
        'image/webp': '.webp', 'image/bmp': '.bmp', 'image/svg+xml': '.svg',
        'audio/mpeg': '.mp3', 'audio/wav': '.wav', 'audio/mp4': '.m4a',
        'audio/ogg': '.ogg', 'audio/flac': '.flac', 'audio/aac': '.aac',
        'video/mp4': '.mp4', 'video/webm': '.webm', 'video/quicktime': '.mov',
    };
    const ext = extMap[mimeType] || '.bin';
    const filename = `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 6)}${ext}`;
    const filePath = path.join(dir, filename);
    // Write base64 data to file
    const buffer = Buffer.from(base64Data, 'base64');
    fs.writeFileSync(filePath, buffer);
    const url = `/api/pure-agent/conv-files/${convId}/${filename}`;
    (0, logger_1.getLogger)().debug(`Saved media file: ${filename} (${buffer.length} bytes)`);
    return { filename, filePath, url };
}
// ---------------------------------------------------------------------------
// Save text file
// ---------------------------------------------------------------------------
function saveTextFile(convId, content, filename) {
    const dir = ensureConvDir(convId);
    const filePath = path.join(dir, filename);
    fs.writeFileSync(filePath, content, 'utf-8');
    const url = `/api/pure-agent/conv-files/${convId}/${filename}`;
    return { filename, filePath, url };
}
function extractAndSaveMedia(convId, contentBlocks) {
    const mediaFiles = [];
    const processed = [];
    for (const block of contentBlocks) {
        if (block.type === 'image_url' && block.image_url?.url?.startsWith('data:')) {
            // Extract base64 from data URL
            const match = block.image_url.url.match(/^data:(image\/\w+);base64,(.+)$/);
            if (match) {
                const [, mimeType, base64] = match;
                const saved = saveMediaFile(convId, base64, mimeType, 'img');
                mediaFiles.push(saved.filename);
                // Replace with file URL reference
                processed.push({
                    type: 'image_url',
                    image_url: { url: saved.url },
                    _file: saved.filename,
                });
                continue;
            }
        }
        if (block.type === 'input_audio' && block.input_audio?.data) {
            const format = block.input_audio.format || 'mp3';
            const mimeMap = {
                mp3: 'audio/mpeg', wav: 'audio/wav', m4a: 'audio/mp4',
                ogg: 'audio/ogg', flac: 'audio/flac', aac: 'audio/aac',
            };
            const mimeType = mimeMap[format] || 'audio/mpeg';
            const saved = saveMediaFile(convId, block.input_audio.data, mimeType, 'audio');
            mediaFiles.push(saved.filename);
            processed.push({
                type: 'input_audio',
                input_audio: { url: saved.url, format },
                _file: saved.filename,
            });
            continue;
        }
        if (block.type === 'video_url' && block.video_url?.url?.startsWith('data:')) {
            const match = block.video_url.url.match(/^data:(video\/\w+);base64,(.+)$/);
            if (match) {
                const [, mimeType, base64] = match;
                const saved = saveMediaFile(convId, base64, mimeType, 'video');
                mediaFiles.push(saved.filename);
                processed.push({
                    type: 'video_url',
                    video_url: { url: saved.url },
                    _file: saved.filename,
                });
                continue;
            }
        }
        // Non-media block, pass through
        processed.push(block);
    }
    return { content: processed, mediaFiles };
}
// ---------------------------------------------------------------------------
// Load media files back as base64 data URLs for LLM API
// ---------------------------------------------------------------------------
function loadMediaAsBase64(convId, content) {
    return content.map((block) => {
        if (block.type === 'image_url' && block._file) {
            const filePath = path.join(getConvDir(convId), block._file);
            if (fs.existsSync(filePath)) {
                const data = fs.readFileSync(filePath);
                const mime = detectMime(block._file);
                return {
                    ...block,
                    image_url: { url: `data:${mime};base64,${data.toString('base64')}` },
                };
            }
        }
        if (block.type === 'input_audio' && block._file) {
            const filePath = path.join(getConvDir(convId), block._file);
            if (fs.existsSync(filePath)) {
                const data = fs.readFileSync(filePath);
                const format = path.extname(block._file).replace('.', '') || 'mp3';
                return {
                    ...block,
                    input_audio: { data: data.toString('base64'), format },
                };
            }
        }
        if (block.type === 'video_url' && block._file) {
            const filePath = path.join(getConvDir(convId), block._file);
            if (fs.existsSync(filePath)) {
                const data = fs.readFileSync(filePath);
                const mime = detectMime(block._file);
                return {
                    ...block,
                    video_url: { url: `data:${mime};base64,${data.toString('base64')}` },
                };
            }
        }
        return block;
    });
}
function detectMime(filename) {
    const ext = path.extname(filename).toLowerCase();
    const map = {
        '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
        '.gif': 'image/gif', '.webp': 'image/webp', '.bmp': 'image/bmp',
        '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.ogg': 'audio/ogg',
        '.mp4': 'video/mp4', '.webm': 'video/webm', '.mov': 'video/quicktime',
    };
    return map[ext] || 'application/octet-stream';
}
// ---------------------------------------------------------------------------
// Restore media URLs for display
// ---------------------------------------------------------------------------
function resolveMediaUrl(convId, url) {
    if (url.startsWith('/api/pure-agent/conv-files/')) {
        return url;
    }
    if (url.startsWith('http')) {
        return url;
    }
    return `/api/pure-agent/conv-files/${convId}/${url}`;
}
// ---------------------------------------------------------------------------
// Cleanup
// ---------------------------------------------------------------------------
function cleanupConvFiles(convId) {
    const dir = getConvDir(convId);
    try {
        if (fs.existsSync(dir)) {
            fs.rmSync(dir, { recursive: true, force: true });
            (0, logger_1.getLogger)().info(`Cleaned up conv-files for ${convId}`);
        }
    }
    catch { /* ignore */ }
}
//# sourceMappingURL=conv-files.js.map