"use strict";
/**
 * Module: llm/gen/artifacts
 *
 * Helpers for reading persisted dialog artifacts (e.g., MCP screenshots) from disk.
 */
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.isVisionImageMimeType = isVisionImageMimeType;
exports.bytesToDataUrl = bytesToDataUrl;
exports.normalizeDialogArtifactRelPath = normalizeDialogArtifactRelPath;
exports.locateDialogArtifactFilePath = locateDialogArtifactFilePath;
exports.readDialogArtifactBytes = readDialogArtifactBytes;
const promises_1 = __importDefault(require("fs/promises"));
const path = __importStar(require("path"));
const dialog_1 = require("../../dialog");
const persistence_1 = require("../../persistence");
function isVisionImageMimeType(mimeType) {
    switch (mimeType) {
        case 'image/jpeg':
        case 'image/png':
        case 'image/gif':
        case 'image/webp':
            return true;
        default:
            return false;
    }
}
function bytesToDataUrl(params) {
    const base64 = params.bytes.toString('base64');
    return `data:${params.mimeType};base64,${base64}`;
}
function normalizeDialogArtifactRelPath(raw) {
    const trimmed = raw.trim();
    if (trimmed === '')
        return null;
    if (trimmed.includes('\u0000'))
        return null;
    if (trimmed.includes('\\'))
        return null;
    if (trimmed.startsWith('/'))
        return null;
    if (trimmed.includes(':'))
        return null;
    const normalized = path.posix.normalize(trimmed);
    if (!normalized.startsWith('artifacts/'))
        return null;
    if (normalized.endsWith('/'))
        return null;
    const parts = normalized.split('/');
    if (parts.some((p) => p === '' || p === '.' || p === '..'))
        return null;
    return normalized;
}
function ensureTrailingSep(p) {
    return p.endsWith(path.sep) ? p : p + path.sep;
}
function isDialogStatusKind(value) {
    return value === 'running' || value === 'completed' || value === 'archived';
}
async function locateDialogArtifactFilePath(params) {
    const relPath = normalizeDialogArtifactRelPath(params.relPath);
    if (!relPath)
        return null;
    if (!isDialogStatusKind(params.status))
        return null;
    const baseDir = persistence_1.DialogPersistence.getDialogEventsPath(new dialog_1.DialogID(params.selfId, params.rootId), params.status);
    const candidatePath = path.join(baseDir, ...relPath.split('/'));
    const baseAbs = ensureTrailingSep(path.resolve(baseDir));
    const candAbs = path.resolve(candidatePath);
    if (!candAbs.startsWith(baseAbs))
        return null;
    try {
        const st = await promises_1.default.stat(candAbs);
        if (!st.isFile())
            return null;
        return candAbs;
    }
    catch (error) {
        const code = typeof error === 'object' && error !== null && 'code' in error
            ? error.code
            : undefined;
        if (code === 'ENOENT')
            return null;
        throw error;
    }
}
async function readDialogArtifactBytes(params) {
    const absPath = await locateDialogArtifactFilePath(params);
    if (!absPath)
        return null;
    const data = await promises_1.default.readFile(absPath);
    return Buffer.isBuffer(data) ? data : Buffer.from(data);
}
