function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _class_call_check(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
    }
}
function _defineProperties(target, props) {
    for(var i = 0; i < props.length; i++){
        var descriptor = props[i];
        descriptor.enumerable = descriptor.enumerable || false;
        descriptor.configurable = true;
        if ("value" in descriptor) descriptor.writable = true;
        Object.defineProperty(target, descriptor.key, descriptor);
    }
}
function _create_class(Constructor, protoProps, staticProps) {
    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
    if (staticProps) _defineProperties(Constructor, staticProps);
    return Constructor;
}
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 _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
import { FILE_TYPES, FileCategory } from "../types";
var DEFAULT_MIME_TYPE = 'application/octet-stream';
var TEXT_MIME_TYPE = 'text/plain';
var CODE_MIME_TYPES = [
    'text/javascript',
    'application/javascript',
    'text/typescript',
    'application/typescript',
    'text/jsx',
    'text/tsx',
    'text/x-python',
    'application/x-python-code',
    'text/x-java-source',
    'text/x-c++src',
    'text/x-c++hdr',
    'text/x-csrc',
    'text/x-chdr',
    'text/x-csharp',
    'text/x-go',
    'text/x-rust',
    'text/x-php',
    'application/x-httpd-php',
    'text/x-ruby',
    'text/x-shellscript',
    'application/x-sh',
    'text/x-powershell',
    'text/x-sql',
    'application/sql',
    'text/x-kotlin',
    'text/x-swift',
    'text/x-dart',
    'text/x-lua',
    'text/x-perl',
    'text/x-r',
    'text/x-matlab',
    'text/x-scala',
    'application/json',
    'application/yaml',
    'text/yaml',
    'application/toml'
];
/**
 * 文件数据源枚举
 */ export var DataSourceType = /*#__PURE__*/ function(DataSourceType) {
    DataSourceType["URL"] = "url";
    DataSourceType["CONTENT"] = "content";
    DataSourceType["FILE"] = "file";
    return DataSourceType;
}({});
/**
 * 预览能力枚举
 */ export var PreviewCapability = /*#__PURE__*/ function(PreviewCapability) {
    PreviewCapability["FULL"] = "full";
    PreviewCapability["BASIC"] = "basic";
    PreviewCapability["NONE"] = "none";
    return PreviewCapability;
}({});
/**
 * URL数据源策略
 */ export var UrlDataSourceStrategy = /*#__PURE__*/ function() {
    "use strict";
    function UrlDataSourceStrategy() {
        _class_call_check(this, UrlDataSourceStrategy);
    }
    _create_class(UrlDataSourceStrategy, [
        {
            key: "canHandle",
            value: function canHandle(file) {
                return Boolean(file.url);
            }
        },
        {
            key: "process",
            value: function process(file) {
                if (!file.url) {
                    throw new Error('URL not provided');
                }
                var fileCategory = this.getFileCategory(file);
                return {
                    sourceType: "url",
                    previewCapability: this.getPreviewCapability(fileCategory),
                    previewUrl: file.url,
                    mimeType: this.inferMimeType(file),
                    needsCleanup: false
                };
            }
        },
        {
            key: "getFileCategory",
            value: function getFileCategory(file) {
                var _file_url_split_pop, _file_url;
                var extension = (_file_url = file.url) === null || _file_url === void 0 ? void 0 : (_file_url_split_pop = _file_url.split('.').pop()) === null || _file_url_split_pop === void 0 ? void 0 : _file_url_split_pop.toLowerCase();
                if (!extension) return FileCategory.Other;
                var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
                try {
                    // 根据扩展名判断分类
                    for(var _iterator = Object.entries(FILE_TYPES)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                        var _step_value = _sliced_to_array(_step.value, 2), definition = _step_value[1];
                        if (definition.extensions.includes(extension)) {
                            return definition.category;
                        }
                    }
                } catch (err) {
                    _didIteratorError = true;
                    _iteratorError = err;
                } finally{
                    try {
                        if (!_iteratorNormalCompletion && _iterator.return != null) {
                            _iterator.return();
                        }
                    } finally{
                        if (_didIteratorError) {
                            throw _iteratorError;
                        }
                    }
                }
                return FileCategory.Other;
            }
        },
        {
            key: "getPreviewCapability",
            value: function getPreviewCapability(category) {
                switch(category){
                    case FileCategory.Image:
                        return "basic";
                    default:
                        return "none";
                }
            }
        },
        {
            key: "inferMimeType",
            value: function inferMimeType(file) {
                var _file_url_split_pop, _file_url;
                var extension = (_file_url = file.url) === null || _file_url === void 0 ? void 0 : (_file_url_split_pop = _file_url.split('.').pop()) === null || _file_url_split_pop === void 0 ? void 0 : _file_url_split_pop.toLowerCase();
                if (!extension) return DEFAULT_MIME_TYPE;
                var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
                try {
                    for(var _iterator = Object.entries(FILE_TYPES)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                        var _step_value = _sliced_to_array(_step.value, 2), definition = _step_value[1];
                        if (definition.extensions.includes(extension)) {
                            return definition.mimeTypes[0];
                        }
                    }
                } catch (err) {
                    _didIteratorError = true;
                    _iteratorError = err;
                } finally{
                    try {
                        if (!_iteratorNormalCompletion && _iterator.return != null) {
                            _iterator.return();
                        }
                    } finally{
                        if (_didIteratorError) {
                            throw _iteratorError;
                        }
                    }
                }
                return DEFAULT_MIME_TYPE;
            }
        }
    ]);
    return UrlDataSourceStrategy;
}();
/**
 * 内容数据源策略
 */ export var ContentDataSourceStrategy = /*#__PURE__*/ function() {
    "use strict";
    function ContentDataSourceStrategy() {
        _class_call_check(this, ContentDataSourceStrategy);
    }
    _create_class(ContentDataSourceStrategy, [
        {
            key: "canHandle",
            value: function canHandle(file) {
                return Boolean(file.content);
            }
        },
        {
            key: "process",
            value: function process(file) {
                if (!file.content) {
                    throw new Error('Content not provided');
                }
                var previewUrl;
                if (typeof URL !== 'undefined' && URL.createObjectURL) {
                    var blob = new Blob([
                        file.content
                    ], {
                        type: TEXT_MIME_TYPE
                    });
                    previewUrl = URL.createObjectURL(blob);
                }
                return {
                    sourceType: "content",
                    previewCapability: "full",
                    previewUrl: previewUrl,
                    content: file.content,
                    mimeType: TEXT_MIME_TYPE,
                    needsCleanup: Boolean(previewUrl)
                };
            }
        }
    ]);
    return ContentDataSourceStrategy;
}();
/**
 * File对象数据源策略
 */ export var FileDataSourceStrategy = /*#__PURE__*/ function() {
    "use strict";
    function FileDataSourceStrategy() {
        _class_call_check(this, FileDataSourceStrategy);
    }
    _create_class(FileDataSourceStrategy, [
        {
            key: "canHandle",
            value: function canHandle(file) {
                return Boolean(file.file);
            }
        },
        {
            key: "process",
            value: function process(file) {
                if (!file.file) {
                    throw new Error('File object not provided');
                }
                // 为File对象创建URL（仅在浏览器环境中）
                var previewUrl;
                if (typeof URL !== 'undefined' && URL.createObjectURL) {
                    previewUrl = URL.createObjectURL(file.file);
                }
                var fileCategory = this.getCategoryFromMimeType(file.file.type);
                return {
                    sourceType: "file",
                    previewCapability: this.getPreviewCapability(fileCategory),
                    previewUrl: previewUrl,
                    mimeType: file.file.type,
                    needsCleanup: Boolean(previewUrl)
                };
            }
        },
        {
            key: "getCategoryFromMimeType",
            value: function getCategoryFromMimeType(mimeType) {
                if (mimeType.startsWith('image/')) return FileCategory.Image;
                if (mimeType.startsWith('video/')) return FileCategory.Video;
                // 先识别具体的代码类 MIME，避免被通用的 text/* 提前匹配
                if (this.isCodeMimeType(mimeType)) return FileCategory.Code;
                if (mimeType.startsWith('text/')) return FileCategory.Text;
                if (mimeType === 'application/pdf') return FileCategory.PDF;
                return FileCategory.Other;
            }
        },
        {
            key: "isCodeMimeType",
            value: function isCodeMimeType(mimeType) {
                return CODE_MIME_TYPES.includes(mimeType);
            }
        },
        {
            key: "getPreviewCapability",
            value: function getPreviewCapability(category) {
                switch(category){
                    case FileCategory.Text:
                    case FileCategory.Code:
                    case FileCategory.Image:
                    case FileCategory.Video:
                    case FileCategory.PDF:
                        return "full";
                    default:
                        return "none";
                }
            }
        }
    ]);
    return FileDataSourceStrategy;
}();
/**
 * 数据源管理器
 */ export var DataSourceManager = /*#__PURE__*/ function() {
    "use strict";
    function DataSourceManager() {
        _class_call_check(this, DataSourceManager);
        _define_property(this, "strategies", [
            new ContentDataSourceStrategy(),
            new FileDataSourceStrategy(),
            new UrlDataSourceStrategy()
        ]);
    }
    _create_class(DataSourceManager, [
        {
            /**
   * 处理文件数据源
   */ key: "processFile",
            value: function processFile(file) {
                var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
                try {
                    for(var _iterator = this.strategies[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                        var strategy = _step.value;
                        if (strategy.canHandle(file)) {
                            return strategy.process(file);
                        }
                    }
                } catch (err) {
                    _didIteratorError = true;
                    _iteratorError = err;
                } finally{
                    try {
                        if (!_iteratorNormalCompletion && _iterator.return != null) {
                            _iterator.return();
                        }
                    } finally{
                        if (_didIteratorError) {
                            throw _iteratorError;
                        }
                    }
                }
                // 默认处理
                return {
                    sourceType: "url",
                    previewCapability: "none",
                    needsCleanup: false
                };
            }
        },
        {
            /**
   * 清理资源
   */ key: "cleanupResult",
            value: function cleanupResult(result) {
                var _result_previewUrl;
                if (!result.needsCleanup || !((_result_previewUrl = result.previewUrl) === null || _result_previewUrl === void 0 ? void 0 : _result_previewUrl.startsWith('blob:'))) return;
                // 直接清理 Blob URL，不需要找到具体的策略（仅在浏览器环境中）
                if (typeof URL !== 'undefined' && URL.revokeObjectURL) {
                    URL.revokeObjectURL(result.previewUrl);
                }
            }
        },
        {
            /**
   * 注册新的数据源策略
   */ key: "registerStrategy",
            value: function registerStrategy(strategy) {
                this.strategies.unshift(strategy); // 新策略优先级更高
            }
        }
    ]);
    return DataSourceManager;
}();
/**
 * 全局数据源管理器实例
 */ export var dataSourceManager = new DataSourceManager();
