#include <spdlog/spdlog.h>
#include <algorithm>
#include <cctype>
#include "../../language/keyword/repo.hpp"
#include "../../service/document.hpp"
#include "../../service/symbol.hpp"
#include "../../utils/string.hpp"
#include "../../protocol/transform/facade.hpp"
#include "./completion.hpp"

namespace lsp::provider::text_document
{
    namespace context_analyzer
    {
        CompletionContext Analyze(const protocol::CompletionParams& params, const std::optional<std::string>& document_content)
        {
            CompletionContext result;
            result.uri = params.textDocument.uri;
            result.position = params.position;

            if (!document_content.has_value())
            {
                spdlog::warn("context_analyzer: Document content not available for URI: {}", result.uri);
                return result;
            }

            const std::string& content = *document_content;

            // 定位到光标所在行的起始位置
            size_t line_start = 0;
            size_t current_line = 0;
            for (size_t i = 0; i < content.length(); ++i)
            {
                if (current_line == result.position.line)
                {
                    line_start = i;
                    break;
                }
                if (content[i] == '\n')
                {
                    ++current_line;
                }
            }

            size_t cursor_pos = line_start + result.position.character;
            cursor_pos = std::min(cursor_pos, content.length());

            // 提取当前行直到光标位置的内容
            result.line_content = content.substr(line_start, cursor_pos - line_start);

            std::string class_name, method_prefix;
            result.is_class_method_context = IsClassMethodContext(result.line_content, class_name, method_prefix);
            if (result.is_class_method_context)
            {
                result.class_name = class_name;
                result.prefix = method_prefix;
            }
            else
            {
                // 分析上下文类型（按优先级检查）
                result.is_new_context = IsNewContext(result.line_content);
                result.is_unit_context = IsUnitContext(result.line_content);
                result.is_class_context = IsClassContext(result.line_content);

                // 根据上下文类型提取前缀
                if (result.is_new_context)
                    result.prefix = ExtractNewPrefix(result.line_content);
                else if (result.is_unit_context)
                    result.prefix = ExtractUnitPrefix(result.line_content);
                else if (result.is_class_context)
                    result.prefix = ExtractClassPrefix(result.line_content);
                else
                    result.prefix = ExtractPrefix(cursor_pos, line_start, content);
            }
            return result;
        }

        bool IsNewContext(const std::string& line)
        {
            std::string line_lower = utils::ToLower(line);
            size_t new_pos = line_lower.rfind("new ");

            if (new_pos == std::string::npos)
                return false;

            std::string after_new = utils::Trim(line.substr(new_pos + 4));

            // 如果 new 后面已经有左括号，说明已经开始构造调用，不再是类名补全上下文
            if (after_new.find('(') != std::string::npos)
                return false;

            return true;
        }

        bool IsClassMethodContext(const std::string& line, std::string& out_class_name, std::string& out_prefix)
        {
            std::string line_lower = utils::ToLower(line);

            // 查找 class( 模式
            size_t class_pos = line_lower.rfind("class(");
            if (class_pos == std::string::npos)
                return false;

            // 提取 class( 之后的内容
            std::string after_class = line.substr(class_pos + 6);

            // 查找右括号和点号
            size_t close_paren = after_class.find(')');
            if (close_paren == std::string::npos)
                return false;

            size_t dot_pos = after_class.find('.', close_paren);
            if (dot_pos == std::string::npos)
                return false;

            // 提取类名（括号内的内容）
            out_class_name = utils::Trim(after_class.substr(0, close_paren));
            if (out_class_name.empty())
                return false;

            // 提取点号后的前缀
            out_prefix = utils::Trim(after_class.substr(dot_pos + 1));

            return true;
        }

        bool IsUnitContext(const std::string& line)
        {
            std::string line_lower = utils::ToLower(line);

            // 检查 "unit(" 模式
            size_t unit_pos = line_lower.rfind("unit(");
            if (unit_pos == std::string::npos)
                return false;

            // 确保 unit( 后面没有闭合括号
            size_t after_paren = unit_pos + 5;
            std::string after = line.substr(after_paren);

            if (after.find(')') != std::string::npos)
                return false;

            return true;
        }

        bool IsClassContext(const std::string& line)
        {
            std::string line_lower = utils::ToLower(line);

            // 检查 "class(" 模式
            size_t class_pos = line_lower.rfind("class(");
            if (class_pos == std::string::npos)
                return false;

            // 确保 class( 后面没有闭合括号
            size_t after_paren = class_pos + 6;
            std::string after = line.substr(after_paren);

            if (after.find(')') != std::string::npos)
                return false;

            return true;
        }

        std::string ExtractPrefix(size_t cursor_pos, size_t line_start, const std::string& content)
        {
            size_t prefix_start = cursor_pos;

            while (prefix_start > line_start)
            {
                char ch = content[prefix_start - 1];
                if (!std::isalnum(ch) && ch != '_')
                {
                    break;
                }
                --prefix_start;
            }

            return content.substr(prefix_start, cursor_pos - prefix_start);
        }

        std::string ExtractNewPrefix(const std::string& line)
        {
            std::string line_lower = utils::ToLower(line);
            size_t new_pos = line_lower.rfind("new ");

            if (new_pos == std::string::npos)
                return "";

            return utils::Trim(line.substr(new_pos + 4));
        }

        std::string ExtractUnitPrefix(const std::string& line)
        {
            std::string line_lower = utils::ToLower(line);
            size_t unit_pos = line_lower.rfind("unit(");

            if (unit_pos == std::string::npos)
                return "";

            return utils::Trim(line.substr(unit_pos + 5));
        }

        std::string ExtractClassPrefix(const std::string& line)
        {
            std::string line_lower = utils::ToLower(line);
            size_t class_pos = line_lower.rfind("class(");

            if (class_pos == std::string::npos)
                return "";

            return utils::Trim(line.substr(class_pos + 6));
        }
    }

    std::string Completion::GetMethod() const
    {
        return "textDocument/completion";
    }

    std::string Completion::GetProviderName() const
    {
        return "TextDocumentCompletion";
    }

    std::string Completion::ProvideResponse(const protocol::RequestMessage& request, ExecutionContext& execution_context)
    {
        spdlog::debug("{}: Processing completion request", GetProviderName());

        if (!request.params.has_value())
        {
            spdlog::warn("{}: Missing params in request", GetProviderName());
            return BuildErrorResponseMessage(request, protocol::ErrorCodes::InvalidParams, "Missing params");
        }

        protocol::CompletionParams completion_params = transform::As<protocol::CompletionParams>(request.params.value());
        protocol::CompletionList completion_list = BuildCompletionList(completion_params, execution_context);

        protocol::ResponseMessage response;
        response.id = request.id;
        response.result = transform::LSPAny(completion_list);

        std::optional<std::string> json = transform::Serialize(response);
        if (!json.has_value())
            return BuildErrorResponseMessage(request, protocol::ErrorCodes::InternalError, "Failed to serialize response");

        return json.value();
    }

    protocol::CompletionList Completion::BuildCompletionList(const protocol::CompletionParams& params, ExecutionContext& execution_context)
    {
        spdlog::trace("{}: URI='{}', Position=({}, {})", GetProviderName(), params.textDocument.uri, params.position.line, params.position.character);

        auto document_service = execution_context.GetService<service::Document>();
        auto symbol_service = execution_context.GetService<service::Symbol>();
        auto document_content = document_service->GetContent(params.textDocument.uri);
        CompletionContext comp_context = context_analyzer::Analyze(params, document_content);

        spdlog::debug("{}: Completion context - prefix ='{}', is_new_context = {}, is_unit_context = {}, is_class_context = {}, is_class_method_context = {}",
                      GetProviderName(),
                      comp_context.prefix,
                      comp_context.is_new_context,
                      comp_context.is_unit_context,
                      comp_context.is_class_context,
                      comp_context.is_class_method_context
                      );

        std::vector<SourcedCompletionItem> collected_items;

        // 根据上下文类型决定收集哪些补全项
        if (comp_context.is_class_method_context)
        {
            // class(xxx). 上下文：提供指定类的类方法
            auto class_method_items = CollectClassMethods(comp_context, *symbol_service);
            spdlog::trace("{}: Found {} class method completions for class '{}'", GetProviderName(), class_method_items.size(), comp_context.class_name);
            collected_items.insert(collected_items.end(), class_method_items.begin(), class_method_items.end());
        }
        else if (comp_context.is_new_context)
        {
            // new 上下文：提供类名（标记为 new 上下文）
            auto class_items = CollectClassNames(comp_context, *symbol_service, true);
            spdlog::trace("{}: Found {} class completions for new context", GetProviderName(), class_items.size());
            collected_items.insert(collected_items.end(), class_items.begin(), class_items.end());
        }
        else if (comp_context.is_unit_context)
        {
            // unit( 上下文：只提供 Unit 名称
            auto unit_items = CollectUnitNames(comp_context, *symbol_service);
            spdlog::trace("{}: Found {} unit completions", GetProviderName(), unit_items.size());
            collected_items.insert(collected_items.end(), unit_items.begin(), unit_items.end());
        }
        else if (comp_context.is_class_context)
        {
            // class( 上下文：只提供类名
            auto class_items = CollectClassNames(comp_context, *symbol_service, false);
            spdlog::trace("{}: Found {} class completions", GetProviderName(), class_items.size());
            collected_items.insert(collected_items.end(), class_items.begin(), class_items.end());
        }
        else
        {
            // 关键字
            auto keyword_items = CollectKeywords(comp_context.prefix);
            spdlog::trace("{}: Found {} keyword completions", GetProviderName(), keyword_items.size());
            collected_items.insert(collected_items.end(), keyword_items.begin(), keyword_items.end());

            // 当前编辑文档的所有函数
            auto editing_items = CollectEditingFunctions(comp_context, *symbol_service);
            spdlog::trace("{}: Found {} editing functions", GetProviderName(), editing_items.size());
            collected_items.insert(collected_items.end(), editing_items.begin(), editing_items.end());

            // 工作区顶层函数
            auto workspace_items = CollectWorkspaceFunctions(comp_context, *symbol_service);
            spdlog::trace("{}: Found {} workspace functions", GetProviderName(), workspace_items.size());
            collected_items.insert(collected_items.end(), workspace_items.begin(), workspace_items.end());

            // 系统库顶层函数
            auto system_items = CollectSystemFunctions(comp_context, *symbol_service);
            spdlog::trace("{}: Found {} system functions", GetProviderName(), system_items.size());
            collected_items.insert(collected_items.end(), system_items.begin(), system_items.end());
        }

        std::vector<protocol::CompletionItem> sorted_items = FilterAndSort(collected_items, comp_context.prefix);

        protocol::CompletionList result;
        result.isIncomplete = false;
        result.items = std::move(sorted_items);
        spdlog::info("{}: Provided {} completion items for prefix '{}'", GetProviderName(), result.items.size(), comp_context.prefix);
        return result;
    }

    // ==================== 符号收集函数 ====================

    std::vector<SourcedCompletionItem> Completion::CollectKeywords(const std::string& prefix)
    {
        std::vector<SourcedCompletionItem> items;
        auto keywords_item = language::keyword::Repo::Instance().FindByPrefix(utils::ToLower(prefix));
        for (const auto& keyword : keywords_item)
        {
            protocol::CompletionItem item;
            item.label = keyword.keyword;
            item.kind = protocol::CompletionItemKind::Keyword;
            item.labelDetails = protocol::CompletionItemLabelDetails{
                .detail = "",
                .description = "[K]"
            };
            items.push_back({ item, CompletionSource::kKeyword });
        }
        return items;
    }

    std::vector<SourcedCompletionItem> Completion::CollectClassMethods(const CompletionContext& comp_context, const service::Symbol& symbol_service)
    {
        std::vector<SourcedCompletionItem> items;

        spdlog::debug("CollectClassMethods - Searching for class: '{}', prefix: '{}'", comp_context.class_name, comp_context.prefix);

        // 从工作区查找指定的类
        const auto& workspace_repo = symbol_service.WorkspaceRepo();
        auto class_info = workspace_repo.FindClass(comp_context.class_name);

        if (!class_info.has_value())
        {
            spdlog::warn("CollectClassMethods - Class '{}' not found in workspace",
                         comp_context.class_name);
            return items;
        }

        spdlog::debug("CollectClassMethods - Found class '{}' with {} exported symbols",
                      comp_context.class_name,
                      class_info->exported_symbols.size());

        // 遍历该类的导出符号，收集类方法
        size_t total_members = 0;
        size_t class_methods = 0;
        size_t filtered_by_prefix = 0;

        for (const auto& member : class_info->exported_symbols)
        {
            total_members++;

            spdlog::trace("CollectClassMethods - Member: name='{}', kind={}, is_class_method={}",
                          member.name,
                          static_cast<int>(member.kind),
                          member.is_class_method);

            // 只收集类方法（is_class_method 为 true）
            if (!member.is_class_method)
            {
                spdlog::trace("CollectClassMethods - Skipped '{}' (not a class method)", member.name);
                continue;
            }

            class_methods++;

            // 前缀过滤
            if (!comp_context.prefix.empty() &&
                !utils::IStartsWith(member.name, comp_context.prefix))
            {
                spdlog::trace("CollectClassMethods - Filtered '{}' by prefix", member.name);
                filtered_by_prefix++;
                continue;
            }

            protocol::CompletionItem item;
            item.label = member.name;
            item.kind = ToCompletionItemKind(member.kind);

            // 构建方法签名
            std::string detail = "(";
            for (size_t i = 0; i < member.parameters.size(); ++i)
            {
                if (i > 0)
                    detail += ", ";
                detail += member.parameters[i].name;
                if (!member.parameters[i].type.empty())
                    detail += ": " + member.parameters[i].type;
            }
            detail += ")";
            if (member.return_type.has_value())
                detail += ": " + *member.return_type;

            item.labelDetails = protocol::CompletionItemLabelDetails{
                .detail = detail,
                .description = "[W]"
            };

            CompletionInfo ci = {.type = "class_method_context", .class_name = comp_context.class_name};
            item.data = transform::LSPAnyConverter::ToLSPAny<CompletionInfo>(ci);

            spdlog::debug("CollectClassMethods - Added class method: {} {}", member.name, detail);
            items.push_back({ item, CompletionSource::kWorkspace });
        }

        spdlog::info("CollectClassMethods - Class '{}': total_members={}, class_methods={}, filtered_by_prefix={}, result_count={}",
                     comp_context.class_name,
                     total_members,
                     class_methods,
                     filtered_by_prefix,
                     items.size());

        return items;
    }

    std::vector<SourcedCompletionItem> Completion::CollectUnitNames(const CompletionContext& comp_context, const service::Symbol& symbol_service)
    {
        std::vector<SourcedCompletionItem> items;

        // 从工作区收集 Unit 名称
        const auto& workspace_repo = symbol_service.WorkspaceRepo();
        auto units = workspace_repo.Units();

        for (const auto& file_index : units)
        {
            if (comp_context.prefix.empty() ||
                utils::IStartsWith(file_index.primary_symbol, comp_context.prefix))
            {
                protocol::CompletionItem item;
                item.label = file_index.primary_symbol;
                item.kind = protocol::CompletionItemKind::Module;
                item.labelDetails = protocol::CompletionItemLabelDetails{
                    .detail = "",
                    .description = "[W]"
                };
                // 添加上下文标记
                item.data = protocol::LSPAny("unit_context");
                items.push_back({ item, CompletionSource::kWorkspace });
            }
        }

        // 从系统库收集 Unit 名称
        // const auto& system_repo = symbol_service.SystemRepo();
        // auto system_units = system_repo.Units();

        // for (const auto& sys_index : system_units)
        // {
        //     if (comp_context.prefix.empty() ||
        //         utils::IStartsWith(sys_index.primary_symbol, comp_context.prefix))
        //     {
        //         protocol::CompletionItem item;
        //         item.label = sys_index.primary_symbol;
        //         item.kind = protocol::CompletionItemKind::Module;
        //         item.labelDetails = protocol::CompletionItemLabelDetails{
        //             .detail = "",
        //             .description = "[S]"
        //         };
        //         // 添加上下文标记
        //         item.data = protocol::LSPAny("unit_context");
        //         items.push_back({ item, CompletionSource::kSystem });
        //     }
        // }

        return items;
    }

    std::vector<SourcedCompletionItem> Completion::CollectClassNames(const CompletionContext& comp_context, const service::Symbol& symbol_service, bool is_new_context)
    {
        std::vector<SourcedCompletionItem> items;

        // 从工作区收集类名
        const auto& workspace_repo = symbol_service.WorkspaceRepo();
        auto classes = workspace_repo.Classes();

        for (const auto& file_index : classes)
        {
            if (comp_context.prefix.empty() ||
                utils::IStartsWith(file_index.primary_symbol, comp_context.prefix))
            {
                protocol::CompletionItem item;
                item.label = file_index.primary_symbol;
                item.kind = protocol::CompletionItemKind::Class;
                item.labelDetails = protocol::CompletionItemLabelDetails{
                    .detail = "",
                    .description = "[W]"
                };

                if (is_new_context)
                    item.data = protocol::LSPAny("new_context");
                else
                    item.data = protocol::LSPAny("class_context");

                items.push_back({ item, CompletionSource::kWorkspace });
            }
        }

        // 从系统库收集类名
        // const auto& system_repo = symbol_service.SystemRepo();
        // auto system_classes = system_repo.Classes();

        // for (const auto& sys_index : system_classes)
        // {
        //     if (comp_context.prefix.empty() ||
        //         utils::IStartsWith(sys_index.primary_symbol, comp_context.prefix))
        //     {
        //         protocol::CompletionItem item;
        //         item.label = sys_index.primary_symbol;
        //         item.kind = protocol::CompletionItemKind::Class;
        //         item.labelDetails = protocol::CompletionItemLabelDetails{
        //             .detail = "",
        //             .description = "[S]"
        //         };

        //         if (is_new_context)
        //             item.data = protocol::LSPAny("new_context");
        //         else
        //             item.data = protocol::LSPAny("class_context");

        //         items.push_back({ item, CompletionSource::kSystem });
        //     }
        // }

        return items;
    }

    std::vector<SourcedCompletionItem> Completion::CollectEditingFunctions(const CompletionContext& comp_context, const service::Symbol& symbol_service)
    {
        std::vector<SourcedCompletionItem> items;

        spdlog::trace("CollectEditingFunctions - URI: {}, Prefix: '{}'",
                      comp_context.uri,
                      comp_context.prefix);

        const auto& editing_repo = symbol_service.EditingRepo();
        const auto* symbol_table = editing_repo.GetSymbolTable(comp_context.uri);

        if (!symbol_table)
        {
            spdlog::trace("CollectEditingFunctions - No symbol table for URI: {}", comp_context.uri);
            return items;
        }

        // 获取所有顶层符号
        auto top_level_symbols = symbol_table->GetDocumentSymbols();

        spdlog::trace("CollectEditingFunctions - Found {} top-level symbols", top_level_symbols.size());

        for (const auto* def : top_level_symbols)
        {
            // 跳过全局命名空间
            if (def->name == "::")
                continue;

            // 只收集函数
            if (def->kind != protocol::SymbolKind::Function)
                continue;

            // 前缀过滤
            if (!comp_context.prefix.empty() &&
                !utils::IStartsWith(def->name, comp_context.prefix))
                continue;

            protocol::CompletionItem item;
            item.label = def->name;
            item.kind = ToCompletionItemKind(def->kind);

            // 使用已格式化的签名
            std::string detail = def->detail.empty() ? "()" : def->detail;

            item.labelDetails = protocol::CompletionItemLabelDetails{
                .detail = detail,
                .description = "[E]" // Editing document
            };

            spdlog::trace("CollectEditingFunctions - Added: {} {}", def->name, detail);
            items.push_back({ item, CompletionSource::kEditing });
        }

        spdlog::debug("CollectEditingFunctions - Collected {} functions", items.size());
        return items;
    }

    std::vector<SourcedCompletionItem> Completion::CollectWorkspaceFunctions(const CompletionContext& comp_context, const service::Symbol& symbol_service)
    {
        std::vector<SourcedCompletionItem> items;

        const auto& workspace_repo = symbol_service.WorkspaceRepo();

        // 获取所有工作区函数
        auto functions = workspace_repo.Functions();

        for (const auto& file_index : functions)
        {
            if (comp_context.prefix.empty() || utils::IStartsWith(file_index.primary_symbol, comp_context.prefix))
            {
                protocol::CompletionItem item;
                item.label = file_index.primary_symbol;
                item.kind = ToCompletionItemKind(file_index.primary_kind);

                std::string detail = "";
                // 查找与 primary_symbol 匹配的导出符号以获取详细信息
                for (const auto& exported_sym : file_index.exported_symbols)
                {
                    if (exported_sym.name == file_index.primary_symbol)
                    {
                        // 构建参数列表
                        detail = "(";
                        for (size_t i = 0; i < exported_sym.parameters.size(); ++i)
                        {
                            if (i > 0)
                                detail += ", ";
                            detail += exported_sym.parameters[i].name;
                            if (!exported_sym.parameters[i].type.empty())
                                detail += ": " + exported_sym.parameters[i].type;
                        }
                        detail += ")";

                        // 添加返回类型
                        if (exported_sym.return_type.has_value())
                            detail += ": " + *exported_sym.return_type;

                        break;
                    }
                }

                item.labelDetails = protocol::CompletionItemLabelDetails{
                    .detail = detail,
                    .description = "[W]"
                };
                items.push_back({ item, CompletionSource::kWorkspace });
            }
        }

        return items;
    }

    std::vector<SourcedCompletionItem> Completion::CollectSystemFunctions(const CompletionContext& comp_context, const service::Symbol& symbol_service)
    {
        std::vector<SourcedCompletionItem> items;

        const auto& system_repo = symbol_service.SystemRepo();
        auto functions = system_repo.Functions();

        for (const auto& file_index : functions)
        {
            if (comp_context.prefix.empty() ||
                utils::IStartsWith(file_index.primary_symbol, comp_context.prefix))
            {
                protocol::CompletionItem item;
                item.label = file_index.primary_symbol;
                item.kind = ToCompletionItemKind(file_index.primary_kind);

                std::string detail = "";
                // 查找与 primary_symbol 匹配的导出符号以获取详细信息
                for (const auto& exported_sym : file_index.exported_symbols)
                {
                    if (exported_sym.name == file_index.primary_symbol)
                    {
                        // 构建参数列表
                        detail = "(";
                        for (size_t i = 0; i < exported_sym.parameters.size(); ++i)
                        {
                            if (i > 0)
                                detail += ", ";
                            detail += exported_sym.parameters[i].name;
                            if (!exported_sym.parameters[i].type.empty())
                                detail += ": " + exported_sym.parameters[i].type;
                        }
                        detail += ")";

                        // 添加返回类型
                        if (exported_sym.return_type.has_value())
                            detail += ": " + *exported_sym.return_type;

                        break;
                    }
                }

                item.labelDetails = protocol::CompletionItemLabelDetails{
                    .detail = detail,
                    .description = "[W]"
                };
                items.push_back({ item, CompletionSource::kWorkspace });
            }
        }

        return items;
    }

    // ==================== 过滤和排序 ====================

    std::vector<protocol::CompletionItem> Completion::FilterAndSort(const std::vector<SourcedCompletionItem>& items, const std::string& prefix)
    {
        // 过滤重复项和不匹配项
        std::vector<const SourcedCompletionItem*> unique_items;
        std::set<std::string> seen_labels;

        for (const auto& item : items)
        {
            // 去重
            if (seen_labels.count(item.item.label) > 0)
                continue;
            seen_labels.insert(item.item.label);

            // 前缀过滤（大小写不敏感）
            if (!prefix.empty() &&
                !utils::IStartsWith(item.item.label, prefix))
                continue;

            unique_items.push_back(&item);
        }

        // 排序
        std::sort(unique_items.begin(), unique_items.end(), [&prefix](const SourcedCompletionItem* a, const SourcedCompletionItem* b) -> bool {
            // 1. 完全匹配最优先
            std::string a_lower = utils::ToLower(a->item.label);
            std::string b_lower = utils::ToLower(b->item.label);
            std::string prefix_lower = utils::ToLower(prefix);

            bool a_exact = (a_lower == prefix_lower);
            bool b_exact = (b_lower == prefix_lower);

            if (a_exact != b_exact)
            {
                return a_exact;
            }

            // 2. 匹配分数（前缀匹配程度）
            if (!prefix.empty())
            {
                int a_score = GetMatchScore(a->item.label, prefix);
                int b_score = GetMatchScore(b->item.label, prefix);

                if (a_score != b_score)
                {
                    return a_score > b_score;
                }
            }

            // 3. 来源优先级：Editing > Workspace > System > Keyword
            if (a->source != b->source)
            {
                static auto get_source_priority = [](CompletionSource source) -> int {
                    switch (source)
                    {
                    case CompletionSource::kEditing:
                        return 0;
                    case CompletionSource::kWorkspace:
                        return 1;
                    case CompletionSource::kSystem:
                        return 2;
                    case CompletionSource::kKeyword:
                        return 3;
                    default:
                        return 4;
                    }
                };

                return get_source_priority(a->source) < get_source_priority(b->source);
            }

            // 4. 字母顺序
            return a_lower < b_lower;
        });

        // 构建最终结果
        std::vector<protocol::CompletionItem> result;
        result.reserve(unique_items.size());

        for (const auto* sourced_item : unique_items)
        {
            result.push_back(sourced_item->item);
        }

        spdlog::trace("Filtered {} items to {} unique items", items.size(), result.size());

        return result;
    }

    int Completion::GetMatchScore(const std::string& label, const std::string& prefix)
    {
        if (prefix.empty())
        {
            return 0;
        }

        std::string label_lower = utils::ToLower(label);
        std::string prefix_lower = utils::ToLower(prefix);

        // 如果不是前缀匹配，返回0分
        if (!utils::StartsWith(label_lower, prefix_lower))
            return 0;

        // 基础分数：前缀占标签长度的比例（0-100）
        int base_score = (static_cast<int>(prefix.length()) * 100) / static_cast<int>(label.length());

        // 大小写完全匹配额外加分
        bool case_match = label.substr(0, prefix.length()) == prefix;
        int case_bonus = case_match ? 10 : 0;

        // 长度匹配加分（标签越短越好）
        int length_bonus = 0;
        if (label.length() == prefix.length())
        {
            length_bonus = 20; // 完全匹配长度
        }
        else if (label.length() <= prefix.length() + 3)
        {
            length_bonus = 10; // 接近匹配长度
        }

        return base_score + case_bonus + length_bonus;
    }

    // ==================== 辅助函数 ====================

    protocol::CompletionItemKind Completion::ToCompletionItemKind(language::symbol::SymbolKind kind)
    {
        using language::symbol::SymbolKind;

        switch (kind)
        {
        case SymbolKind::Function:
        case SymbolKind::Method:
            return protocol::CompletionItemKind::Function;
        case SymbolKind::Constructor:
            return protocol::CompletionItemKind::Constructor;
        case SymbolKind::Class:
            return protocol::CompletionItemKind::Class;
        case SymbolKind::Property:
            return protocol::CompletionItemKind::Property;
        case SymbolKind::Variable:
        case SymbolKind::TypeParameter:
            return protocol::CompletionItemKind::Variable;
        case SymbolKind::Constant:
            return protocol::CompletionItemKind::Constant;
        case SymbolKind::Module:
            return protocol::CompletionItemKind::Module;
        default:
            return protocol::CompletionItemKind::Text;
        }
    }

}
