function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
        });
    }
    return target;
}
import json5 from "json5";
import { debugInfo } from "../../../../Utils/debugUtils";
import { isCodeBlockLikelyComplete } from "../../utils/findMatchingClose";
import partialJsonParse from "../json-parse";
// 代码块检测相关的常量
var NOT_SPACE_START = /^\S*/;
var ENDING_NEWLINE = /\n$/;
/**
 * 处理schema类型语言的辅助函数
 */ var processSchemaLanguage = function(element, value) {
    var json = [];
    try {
        json = json5.parse(value || '[]');
    } catch (unused) {
        try {
            json = partialJsonParse(value || '[]');
        } catch (error) {
            json = value;
            console.error('parse schema error', error);
        }
    }
    return _object_spread_props(_object_spread({}, element), {
        type: 'apaasify',
        value: json,
        children: [
            {
                text: value
            }
        ]
    });
};
/**
 * 语言类型处理策略配置
 */ var LANGUAGE_HANDLERS = {
    mermaid: function(element) {
        return _object_spread_props(_object_spread({}, element), {
            type: 'mermaid'
        });
    },
    schema: processSchemaLanguage,
    apaasify: processSchemaLanguage,
    apassify: processSchemaLanguage,
    katex: function(element) {
        return _object_spread_props(_object_spread({}, element), {
            type: 'katex'
        });
    },
    'agentar-card': processSchemaLanguage
};
/**
 * 处理代码块节点
 * @param currentElement - 当前处理的代码块元素，包含语言和内容
 * @param config - 可选的配置对象，可能包含从 HTML 注释中解析的属性
 * @returns 返回格式化的代码块节点对象，根据语言类型进行特殊处理
 */ export var handleCode = function(currentElement, config) {
    var _currentElement_value, _effectiveLang_match, _currentElement_otherProps, _currentElement_value_trim, _resultWithProps_value;
    debugInfo('handleCode - 处理代码块', {
        rawValueLength: (_currentElement_value = currentElement.value) === null || _currentElement_value === void 0 ? void 0 : _currentElement_value.length,
        lang: currentElement.lang,
        configLanguage: config === null || config === void 0 ? void 0 : config['data-language'],
        meta: currentElement.meta
    });
    var rawValue = currentElement.value || '';
    // 如果 config 中包含 data-language，优先使用它来恢复语言类型
    var configLanguage = config === null || config === void 0 ? void 0 : config['data-language'];
    // 保持原有的行为：如果没有语言，应该使用 null 而不是空字符串
    var effectiveLang = configLanguage || currentElement.lang || null;
    var langString = effectiveLang ? ((_effectiveLang_match = effectiveLang.match(NOT_SPACE_START)) === null || _effectiveLang_match === void 0 ? void 0 : _effectiveLang_match[0]) || '' : '';
    debugInfo('handleCode - 语言处理', {
        effectiveLang: effectiveLang,
        langString: langString
    });
    var code = "".concat(rawValue.replace(ENDING_NEWLINE, ''), "\n");
    // 检查代码块是否完整
    // 如果是缩进代码块，认为是完整的（因为没有结束标记）
    var isIndentedCode = currentElement.meta === 'indented';
    // 使用更智能的方法判断代码块是否完整
    var streamStatus = 'loading';
    if (isIndentedCode) {
        // 缩进代码块没有结束标记，认为是完整的
        streamStatus = 'done';
    } else {
        // 对于围栏代码块，使用多种方法判断
        var endsWithNewline = code.match(ENDING_NEWLINE);
        // 如果代码以换行结尾，可能是完整的
        if (endsWithNewline) {
            // 进一步检查代码内容是否完整（特别是对于 Mermaid 等需要完整语法的情况）
            var isLikelyComplete = isCodeBlockLikelyComplete(rawValue, currentElement.lang);
            streamStatus = isLikelyComplete ? 'done' : 'loading';
        } else {
            // 没有换行结尾，肯定不完整
            streamStatus = 'loading';
        }
    }
    // 如果已经在 parseNodes 中设置了 finished（基于是否是最后一个节点），优先使用它
    // 否则使用 streamStatus 判断
    var finishValue = ((_currentElement_otherProps = currentElement.otherProps) === null || _currentElement_otherProps === void 0 ? void 0 : _currentElement_otherProps.finished) !== undefined ? currentElement.otherProps.finished : streamStatus === 'done';
    // 只保留必要的属性，不添加 data-block、data-state、data-language 到 otherProps
    // 这些属性会被序列化为 HTML 注释，造成冗余
    var otherProps = _object_spread({}, currentElement.otherProps || {});
    // 只有未完成时才添加 finished 属性
    if (finishValue === false) {
        otherProps.finished = false;
    }
    var baseCodeElement = {
        type: 'code',
        language: effectiveLang === 'apaasify' ? 'apaasify' : effectiveLang || null,
        render: currentElement.meta === 'render',
        value: currentElement.value,
        isConfig: currentElement === null || currentElement === void 0 ? void 0 : (_currentElement_value_trim = currentElement.value.trim()) === null || _currentElement_value_trim === void 0 ? void 0 : _currentElement_value_trim.startsWith('<!--'),
        children: [
            {
                text: currentElement.value
            }
        ],
        // 添加流式状态支持
        otherProps: otherProps
    };
    var handler = LANGUAGE_HANDLERS[effectiveLang];
    debugInfo('handleCode - 语言处理器', {
        effectiveLang: effectiveLang,
        hasHandler: !!handler,
        handlerName: handler ? Object.keys(LANGUAGE_HANDLERS).find(function(k) {
            return LANGUAGE_HANDLERS[k] === handler;
        }) : undefined
    });
    var result = handler ? handler(baseCodeElement, currentElement.value) : baseCodeElement;
    // 确保 otherProps 被保留，并合并 config 中的属性
    var resultWithProps = result;
    if (baseCodeElement.otherProps && !resultWithProps.otherProps) {
        resultWithProps.otherProps = _object_spread({}, baseCodeElement.otherProps, config || {});
    } else if (baseCodeElement.otherProps && resultWithProps.otherProps) {
        resultWithProps.otherProps = _object_spread({}, resultWithProps.otherProps, baseCodeElement.otherProps, config || {});
    } else if (config && Object.keys(config).length > 0) {
        resultWithProps.otherProps = _object_spread({}, resultWithProps.otherProps || {}, config);
    }
    debugInfo('handleCode - 代码块处理完成', {
        type: resultWithProps.type,
        language: resultWithProps.language,
        render: resultWithProps.render,
        isConfig: resultWithProps.isConfig,
        valueLength: (_resultWithProps_value = resultWithProps.value) === null || _resultWithProps_value === void 0 ? void 0 : _resultWithProps_value.length,
        hasOtherProps: !!resultWithProps.otherProps,
        otherPropsKeys: resultWithProps.otherProps ? Object.keys(resultWithProps.otherProps) : []
    });
    return resultWithProps;
};
/**
 * 处理YAML节点
 * @param currentElement - 当前处理的YAML元素
 * @returns 返回格式化的YAML代码块节点对象
 */ export var handleYaml = function(currentElement) {
    var _currentElement_value;
    debugInfo('handleYaml - 处理 YAML', {
        valueLength: (_currentElement_value = currentElement.value) === null || _currentElement_value === void 0 ? void 0 : _currentElement_value.length
    });
    var result = {
        type: 'code',
        language: 'yaml',
        value: currentElement.value,
        frontmatter: true,
        children: [
            {
                text: currentElement.value
            }
        ]
    };
    debugInfo('handleYaml - YAML 处理完成', {
        type: result.type,
        language: result.language,
        frontmatter: result.frontmatter
    });
    return result;
};
