import { SANDBOX_UPLOADS_PATH } from '../host-tools/sandbox-llm/index.js';
const SPREADSHEET_EXTENSIONS = new Set(['.xlsx', '.xls']);
const MAX_PROMPT_STRING_LENGTH = 255;
function basename(name) {
    const parts = name.split(/[\\/]+/);
    return parts[parts.length - 1] ?? name;
}
function lowerExt(name) {
    const idx = name.lastIndexOf('.');
    return idx < 0 ? '' : name.slice(idx).toLowerCase();
}
function stem(name) {
    const idx = name.lastIndexOf('.');
    return idx < 0 ? name : name.slice(0, idx);
}
function formatBytes(bytes) {
    if (bytes < 1024)
        return `${bytes} B`;
    if (bytes < 1024 * 1024)
        return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
/** Strip path traversal segments and prompt-hostile characters from each segment. */
function sanitizeStoragePath(storageName) {
    return storageName
        .split(/[\\/]+/)
        .filter((part) => part !== '..' && part !== '.' && part !== '')
        .map(sanitizeForPrompt)
        .filter((part) => part.length > 0)
        .join('/');
}
/** Collapse newlines, strip markdown control chars, truncate. */
function sanitizeForPrompt(value) {
    return value
        .replace(/[\r\n]+/g, ' ')
        .replace(/[*#\[\]`]/g, '')
        .replace(/\s{2,}/g, ' ')
        .trim()
        .slice(0, MAX_PROMPT_STRING_LENGTH);
}
function sizeSuffix(fileSize) {
    return fileSize ? ` (${formatBytes(fileSize)})` : '';
}
function fallbackAttachmentId(originalName) {
    return stem(originalName).toLowerCase().replace(/\s+/g, '_');
}
/** Display name; if sanitization stripped everything to just an extension or empty, fall back. */
function displayName(rawName, storageName) {
    const sanitized = sanitizeForPrompt(basename(rawName));
    if (sanitized && stem(sanitized).length > 0)
        return sanitized;
    if (storageName) {
        const fromStorage = sanitizeForPrompt(basename(storageName));
        if (fromStorage && stem(fromStorage).length > 0)
            return fromStorage;
    }
    return 'attachment';
}
function bucketFiles(files) {
    const spreadsheets = [];
    const others = [];
    for (const file of files) {
        const originalName = displayName(file.name, file.storageName);
        const ext = lowerExt(originalName);
        const size = sizeSuffix(file.fileSize);
        if (SPREADSHEET_EXTENSIONS.has(ext)) {
            const attachmentId = sanitizeForPrompt(file.attachmentId ?? fallbackAttachmentId(originalName));
            const storage = file.storageName;
            if (storage) {
                const path = `${SANDBOX_UPLOADS_PATH}/${sanitizeStoragePath(storage)}`;
                spreadsheets.push(`${originalName}${size} -> attachedWorkbook ID: ${attachmentId} | sandbox: ${path}`);
            }
            else {
                spreadsheets.push(`${originalName}${size} -> attachedWorkbook ID: ${attachmentId} (sandbox not available)`);
            }
            continue;
        }
        const storage = file.storageName;
        if (!storage) {
            others.push(`${originalName}${size} -> ⚠️ FILE NOT AVAILABLE (not synced to sandbox - please inform the user)`);
            continue;
        }
        const safe = sanitizeStoragePath(storage);
        const path = `${SANDBOX_UPLOADS_PATH}/${safe}`;
        if (ext === '.pdf') {
            const dataDir = `${SANDBOX_UPLOADS_PATH}/${stem(safe)}/`;
            others.push(`${originalName}${size} -> ${path}\n  - Data folder: ${dataDir}\n  - Index: ${dataDir}index.json (page_count, total_chars, per-page text)`);
        }
        else {
            others.push(`${originalName}${size} -> ${path}`);
        }
    }
    return { spreadsheets, others };
}
/** Build the "User Attached Files" section, or empty string when no files. */
export function buildUploadContextSection(files) {
    if (files.length === 0)
        return '';
    const { spreadsheets, others } = bucketFiles(files);
    const items = [];
    if (spreadsheets.length > 0) {
        items.push('Attached Excel files (call general.getAttachedWorkbookInfo() for API reference):\n' +
            spreadsheets.map((line) => `- ${line}`).join('\n'));
    }
    if (others.length > 0) {
        items.push('Other attached files:\n' + others.map((line) => `- ${line}`).join('\n'));
    }
    if (items.length === 0)
        return '';
    return `\n# User Attached Files (${files.length} files)\n${items.join('\n\n')}\n`;
}
/**
 * Render uploads as a content block on the user `AgentMessage`.
 *
 * Wraps `buildUploadContextSection` to keep one source of truth for the rendered
 * text. Empty input → null (composer drops nulls).
 */
export function buildUploadsBlock(files) {
    if (!files || files.length === 0)
        return null;
    const text = buildUploadContextSection(files);
    if (text.length === 0)
        return null;
    return { type: 'text', text };
}
export const __test__ = {
    basename,
    lowerExt,
    stem,
    formatBytes,
    sanitizeStoragePath,
    sanitizeForPrompt,
    fallbackAttachmentId
};
//# sourceMappingURL=uploads.js.map