using System.Text.RegularExpressions;
using YMhut.Box.Core.Settings;
using YMhut.Box.Core.Tools;
using YMhut.Box.WinUI.Services;

namespace YMhut.Box.WinUI;

internal static class AppLocalizer
{
    private static readonly IReadOnlyDictionary<string, (string Zh, string En)> ToolNames =
        new Dictionary<string, (string Zh, string En)>(StringComparer.OrdinalIgnoreCase)
        {
            ["dev_environment_config"] = ("开发环境配置", "Development Environment Setup"),
            ["json_formatter"] = ("JSON 格式化", "JSON Formatter"),
            ["base64_codec"] = ("Base64 编解码", "Base64 Encoder / Decoder"),
            ["compression_codec"] = ("压缩编解码", "Compression Codec"),
            ["url_codec"] = ("URL 编解码", "URL Encoder / Decoder"),
            ["html_entity"] = ("HTML 实体转换", "HTML Entity Converter"),
            ["html_minifier"] = ("HTML/代码压缩", "HTML / Code Minifier"),
            ["regex_tool"] = ("正则测试", "Regex Tester"),
            ["js_obfuscator"] = ("JS 代码混淆", "JavaScript Obfuscator"),
            ["uuid_generator"] = ("UUID 生成", "UUID Generator"),
            ["ulid_generator"] = ("ULID 生成", "ULID Generator"),
            ["timestamp_converter"] = ("时间戳转换", "Timestamp Converter"),
            ["number_base"] = ("进制转换", "Number Base Converter"),
            ["number_base_converter"] = ("进制转换器", "Number Base Converter"),
            ["csv_json_converter"] = ("CSV/JSON 转换", "CSV / JSON Converter"),
            ["column_extractor"] = ("列提取器", "Column Extractor"),
            ["csv_tsv_converter"] = ("CSV/TSV 转换", "CSV / TSV Converter"),
            ["yaml_json_converter"] = ("YAML/JSON 转换", "YAML / JSON Converter"),
            ["xml_formatter"] = ("XML 格式化", "XML Formatter"),
            ["sql_formatter"] = ("SQL 格式化", "SQL Formatter"),
            ["unicode_codec"] = ("Unicode 转义", "Unicode Escape Converter"),
            ["punycode_codec"] = ("Punycode/IDN 转换", "Punycode / IDN Converter"),
            ["jwt_decoder"] = ("JWT 解码", "JWT Decoder"),
            ["query_builder"] = ("Query 参数构建", "Query Builder"),
            ["form_urlencoded_builder"] = ("表单编码构建", "Form URL Encoded Builder"),
            ["key_value_converter"] = ("键值对转换", "Key / Value Converter"),
            ["cron_helper"] = ("Cron 辅助", "Cron Helper"),
            ["unicode_block_lookup"] = ("Unicode 区段速查", "Unicode Block Lookup"),
            ["charset_lookup"] = ("字符集速查", "Charset Lookup"),
            ["regex_preset_lookup"] = ("正则预设速查", "Regex Preset Lookup"),
            ["magic_number_lookup"] = ("文件头速查", "Magic Number Lookup"),
            ["html_text_extractor"] = ("HTML 正文提取", "HTML Text Extractor"),
            ["slug_generator"] = ("Slug 生成", "Slug Generator"),
            ["markdown_table_normalizer"] = ("Markdown 表格整理", "Markdown Table Normalizer"),
            ["markdown_preview"] = ("Markdown 预览整理", "Markdown Preview / Cleaner"),
            ["json_path_helper"] = ("JSON 路径辅助", "JSON Path Helper"),
            ["hash_generator"] = ("哈希计算", "Hash Generator"),
            ["hmac_generator"] = ("HMAC 生成", "HMAC Generator"),
            ["totp_generator"] = ("TOTP 验证码", "TOTP Generator"),
            ["password_generator"] = ("密码生成", "Password Generator"),
            ["profanity_check"] = ("敏感词检查", "Profanity Check"),
            ["hash_manifest_builder"] = ("哈希清单生成", "Hash Manifest Builder"),
            ["hash_manifest_verify"] = ("哈希清单校验", "Hash Manifest Verifier"),
            ["safe_browser"] = ("安全浏览器", "Safe Browser"),
            ["wx_domain_check"] = ("微信域名检测说明", "WeChat Domain Check"),
            ["ip_lookup"] = ("IP 归属查询", "IP Lookup"),
            ["ip_info"] = ("IP/域名详情", "IP / Domain Info"),
            ["dns_query"] = ("DNS 解析", "DNS Query"),
            ["domain_price"] = ("域名官方信息", "Domain Official Info"),
            ["smart_search"] = ("聚合搜索", "Smart Search"),
            ["rdap_domain_lookup"] = ("域名 RDAP 查询", "Domain RDAP Lookup"),
            ["rdap_ip_lookup"] = ("IP/ASN RDAP 查询", "IP / ASN RDAP Lookup"),
            ["http_diagnostic"] = ("HTTP 诊断", "HTTP Diagnostic"),
            ["url_redirect_trace"] = ("URL 跳转追踪", "URL Redirect Trace"),
            ["url_inspector"] = ("URL 结构解析", "URL Inspector"),
            ["domain_extractor"] = ("域名提取", "Domain Extractor"),
            ["cidr_subnet_calculator"] = ("CIDR 子网计算", "CIDR Subnet Calculator"),
            ["mime_lookup"] = ("MIME 类型速查", "MIME Lookup"),
            ["http_status_lookup"] = ("HTTP 状态码速查", "HTTP Status Lookup"),
            ["port_lookup"] = ("常见端口速查", "Port Lookup"),
            ["dns_record_lookup"] = ("DNS 记录速查", "DNS Record Lookup"),
            ["weather"] = ("天气查询", "Weather"),
            ["hotboard"] = ("综合热榜", "Hotboard"),
            ["bili_hot"] = ("B 站热榜", "Bilibili Hot"),
            ["baidu_hot"] = ("百度热搜", "Baidu Hot Search"),
            ["zhihu_hot"] = ("知乎热榜", "Zhihu Hot"),
            ["cctv_news"] = ("央视新闻", "CCTV News"),
            ["tech_news"] = ("科技新闻", "Tech News"),
            ["football_news"] = ("体育新闻", "Sports News"),
            ["movie_box_office"] = ("电影票房", "Movie Box Office"),
            ["earthquake_info"] = ("地震信息", "Earthquake Info"),
            ["gold_price"] = ("黄金价格", "Gold Price"),
            ["oil_price"] = ("成品油价格政策", "Oil Price Policy"),
            ["train_query"] = ("列车查询", "Train Query"),
            ["history_today"] = ("历史上的今天", "On This Day"),
            ["car_info"] = ("车辆信息", "Vehicle Info"),
            ["sanguosha_skin"] = ("三国杀皮肤", "Sanguosha Skin"),
            ["calculator_tool"] = ("计算器", "Calculator"),
            ["unit_converter"] = ("单位换算", "Unit Converter"),
            ["bmi_calculator"] = ("BMI 计算", "BMI Calculator"),
            ["percentage_calculator"] = ("百分比计算", "Percentage Calculator"),
            ["percentage_change_calculator"] = ("涨跌幅计算", "Percentage Change Calculator"),
            ["discount_calculator"] = ("折扣计算", "Discount Calculator"),
            ["tax_calculator"] = ("税费计算", "Tax Calculator"),
            ["ratio_simplifier"] = ("比例化简", "Ratio Simplifier"),
            ["average_calculator"] = ("平均值计算", "Average Calculator"),
            ["median_calculator"] = ("中位数计算", "Median Calculator"),
            ["gcd_lcm_calculator"] = ("最大公约数/最小公倍数", "GCD / LCM Calculator"),
            ["permutation_calculator"] = ("排列数计算", "Permutation Calculator"),
            ["combination_calculator"] = ("组合数计算", "Combination Calculator"),
            ["date_difference_calculator"] = ("日期差计算", "Date Difference Calculator"),
            ["workday_calculator"] = ("工作日统计", "Workday Calculator"),
            ["age_calculator"] = ("年龄计算", "Age Calculator"),
            ["simple_interest_calculator"] = ("单利计算", "Simple Interest Calculator"),
            ["compound_interest_calculator"] = ("复利计算", "Compound Interest Calculator"),
            ["loan_emi_calculator"] = ("等额本息月供", "Loan EMI Calculator"),
            ["length_converter"] = ("长度换算", "Length Converter"),
            ["weight_converter"] = ("重量换算", "Weight Converter"),
            ["temperature_converter"] = ("温度换算", "Temperature Converter"),
            ["speed_converter"] = ("速度换算", "Speed Converter"),
            ["area_converter"] = ("面积换算", "Area Converter"),
            ["volume_converter"] = ("体积换算", "Volume Converter"),
            ["data_size_converter"] = ("数据容量换算", "Data Size Converter"),
            ["time_duration_converter"] = ("时长换算", "Time Duration Converter"),
            ["text_statistics"] = ("文本统计", "Text Statistics"),
            ["case_converter"] = ("大小写转换", "Case Converter"),
            ["chinese_converter"] = ("简繁转换", "Simplified / Traditional Chinese"),
            ["text_diff"] = ("文本对比", "Text Diff"),
            ["random_generator"] = ("随机生成器", "Random Generator"),
            ["ai_translation"] = ("AI 翻译", "AI Translation"),
            ["ymhut_uutool_suite"] = ("UU 工具合集", "UU Tool Suite"),
            ["text_deduplicator"] = ("文本去重", "Text Deduplicator"),
            ["text_sorter"] = ("文本排序", "Text Sorter"),
            ["text_filter"] = ("文本过滤", "Text Filter"),
            ["delimiter_converter"] = ("分隔符转换", "Delimiter Converter"),
            ["filename_formatter"] = ("文件名格式化", "Filename Formatter"),
            ["text_splitter"] = ("文本拆分", "Text Splitter"),
            ["text_merger"] = ("文本合并", "Text Merger"),
            ["text_numbering"] = ("文本编号", "Text Numbering"),
            ["blank_line_cleaner"] = ("空行清理", "Blank Line Cleaner"),
            ["whitespace_normalizer"] = ("空白规范化", "Whitespace Normalizer"),
            ["prefix_suffix_batch"] = ("前后缀批处理", "Prefix / Suffix Batch"),
            ["line_column_transformer"] = ("行列互转", "Line / Column Transformer"),
            ["list_sampler"] = ("列表抽样", "List Sampler"),
            ["list_chunker"] = ("列表分块", "List Chunker"),
            ["list_intersection"] = ("列表交集", "List Intersection"),
            ["list_union"] = ("列表并集", "List Union"),
            ["list_difference"] = ("列表差集", "List Difference"),
            ["list_group_statistics"] = ("列表分组统计", "List Group Statistics"),
            ["duplicate_detector"] = ("重复项检测", "Duplicate Detector"),
            ["line_length_analyzer"] = ("行长度分析", "Line Length Analyzer"),
            ["keyword_counter"] = ("关键词计数", "Keyword Counter"),
            ["template_filler"] = ("模板填充", "Template Filler"),
            ["path_normalizer"] = ("路径规范化", "Path Normalizer"),
            ["path_breakdown"] = ("路径拆解", "Path Breakdown"),
            ["extension_extractor"] = ("扩展名提取", "Extension Extractor"),
            ["extension_statistics"] = ("扩展名统计", "Extension Statistics"),
            ["file_manifest_builder"] = ("文件清单生成", "File Manifest Builder"),
            ["batch_rename_preview"] = ("批量重命名预览", "Batch Rename Preview"),
            ["indexed_rename_preview"] = ("序号重命名预览", "Indexed Rename Preview"),
            ["manifest_deduplicator"] = ("清单去重", "Manifest Deduplicator"),
            ["manifest_sorter"] = ("清单排序", "Manifest Sorter"),
            ["manifest_template_export"] = ("清单模板导出", "Manifest Template Export"),
            ["text_trimmer"] = ("文本裁剪", "Text Trimmer"),
            ["text_reverser"] = ("文本反转", "Text Reverser"),
            ["markdown_list_cleaner"] = ("Markdown 列表清理", "Markdown List Cleaner"),
            ["line_pair_zipper"] = ("双列合并", "Line Pair Zipper"),
            ["ascii_art"] = ("ASCII 艺术", "ASCII Art"),
            ["color_picker"] = ("颜色工具", "Color Tool"),
            ["color_contrast_checker"] = ("颜色对比度", "Color Contrast Checker"),
            ["qr_generator"] = ("二维码生成", "QR Code Generator"),
            ["qrcode_scanner"] = ("二维码扫描", "QR Code Scanner"),
            ["archive_tool"] = ("归档工具", "Archive Tool"),
            ["image_processor"] = ("图片处理", "Image Processor"),
            ["image_metadata_inspector"] = ("图片元数据", "Image Metadata Inspector"),
            ["media_player"] = ("媒体播放器", "Media Player"),
            ["qq_avatar"] = ("QQ 资料查询", "QQ Profile"),
            ["random_cinema"] = ("随机放映室", "Random Cinema"),
            ["shelf_life"] = ("保质期计算", "Shelf Life Calculator"),
            ["timezone_abbr_lookup"] = ("时区缩写速查", "Timezone Abbreviation Lookup"),
            ["system_info"] = ("系统信息", "System Info"),
            ["system_tool"] = ("系统工具", "System Tools"),
            ["pc_benchmark"] = ("性能跑分", "PC Benchmark")
        };

    internal static bool IsEnglish => string.Equals(CurrentLanguage, "en-US", StringComparison.OrdinalIgnoreCase);

    internal static string CurrentLanguage
    {
        get
        {
            try
            {
                return AppServices.GetRequiredService<ISettingsService>().Current.Language;
            }
            catch
            {
                return "zh-CN";
            }
        }
    }

    internal static string T(string zh, string en) => IsEnglish ? en : zh;

    internal static string ToolName(string id, string fallback = "")
    {
        if (ToolNames.TryGetValue(id, out var name))
        {
            return IsEnglish ? name.En : name.Zh;
        }

        return string.IsNullOrWhiteSpace(fallback) || LooksBroken(fallback) ? Humanize(id) : fallback;
    }

    internal static string ToolNameIn(string id, bool english)
    {
        if (ToolNames.TryGetValue(id, out var name))
        {
            return english ? name.En : name.Zh;
        }

        return Humanize(id);
    }

    internal static string ToolDescription(IToolModule module)
    {
        var name = ToolName(module.Id);
        return module.Metadata.Category switch
        {
            ToolCategory.Plugin => T($"{name} 由插件提供，在独立窗口中隔离运行。", $"{name} is provided by a plugin and runs in an isolated window."),
            ToolCategory.Dev => T($"{name} 使用原生 WinUI 输入与结果预览，适合开发调试。", $"{name} uses native WinUI inputs and previews for development workflows."),
            ToolCategory.Network => T($"{name} 通过共享网络服务获取或解析公开数据，界面不会展示敏感接口地址。", $"{name} uses the shared network service for public data without exposing sensitive endpoints."),
            ToolCategory.Security => T($"{name} 默认在本地执行，适合摘要、校验和安全辅助。", $"{name} runs locally by default for hashes, validation, and security helpers."),
            ToolCategory.Data => T($"{name} 进入页面后加载真实数据源，并以卡片或列表展示。", $"{name} loads live data on open and renders cards or lists."),
            ToolCategory.Calculator => T($"{name} 提供表单式参数输入和结构化计算结果。", $"{name} provides form inputs and structured calculation results."),
            ToolCategory.Text => T($"{name} 针对文本、列表或路径执行本地处理。", $"{name} processes text, lists, or paths locally."),
            ToolCategory.Image => T($"{name} 使用系统文件选择器和原生媒体能力处理文件。", $"{name} uses native file pickers and media capabilities."),
            ToolCategory.Design => T($"{name} 面向颜色、二维码和视觉辅助场景。", $"{name} supports color, QR, and visual helper workflows."),
            ToolCategory.Life => T($"{name} 面向日常查询和生活场景。", $"{name} supports daily lookup and lifestyle workflows."),
            ToolCategory.System => T($"{name} 调用 Windows 原生能力并展示本机摘要。", $"{name} launches Windows-native capabilities and local summaries."),
            _ => T($"{name} 已迁移为 WinUI 3 原生工具页。", $"{name} has been migrated to a native WinUI 3 tool page.")
        };
    }

    internal static string CategoryLabel(ToolCategory category)
    {
        return category switch
        {
            ToolCategory.Plugin => T("插件工具", "Plugin tools"),
            ToolCategory.Dev => T("开发调试", "Developer"),
            ToolCategory.Network => T("网络工具", "Network"),
            ToolCategory.Security => T("安全校验", "Security"),
            ToolCategory.Data => T("数据资讯", "Data"),
            ToolCategory.Calculator => T("计算换算", "Calculator"),
            ToolCategory.Text => T("文本处理", "Text"),
            ToolCategory.Image => T("图像媒体", "Image & Media"),
            ToolCategory.Design => T("设计辅助", "Design"),
            ToolCategory.Life => T("生活查询", "Life"),
            ToolCategory.System => T("系统工具", "System"),
            _ => T("全部工具", "All tools")
        };
    }

    internal static string CategoryHint(ToolCategory category)
    {
        return category switch
        {
            ToolCategory.All => T("全部原生与插件工具", "All native and plugin tools"),
            ToolCategory.Plugin => T("已启用插件提供的工具", "Tools provided by enabled plugins"),
            _ => T("按分类筛选", "Filter by category")
        };
    }

    internal static string ToolCount(int count) => IsEnglish ? $"{count} tools" : $"{count} 个工具";

    internal static string Capability(bool offline) => offline ? T("本地", "Local") : T("联网", "Online");

    internal static string SanitizeSensitiveText(string? message, int maxLength = 120)
    {
        if (string.IsNullOrWhiteSpace(message))
        {
            return T("未知错误", "Unknown error");
        }

        var sanitized = Regex.Replace(
            message,
            @"https?://[^\s\]\)""'<>]+",
            T("远程服务", "remote service"),
            RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

        sanitized = Regex.Replace(
            sanitized,
            @"update\.ymhut\.cn[^\s\]\)""'<>]*",
            T("远程服务", "remote service"),
            RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

        sanitized = sanitized
            .Replace("update-info.json", T("发布服务", "release service"), StringComparison.OrdinalIgnoreCase)
            .Replace("media-types.json", T("媒体配置", "media configuration"), StringComparison.OrdinalIgnoreCase)
            .Replace("api_url", T("媒体源", "media source"), StringComparison.OrdinalIgnoreCase)
            .Replace("download_url", T("下载源", "download source"), StringComparison.OrdinalIgnoreCase);

        if (sanitized.Length <= maxLength)
        {
            return sanitized;
        }

        return sanitized[..Math.Max(0, maxLength - 3)] + "...";
    }

    private static bool LooksBroken(string value)
    {
        return value.Contains('�') || value.Contains("鐢", StringComparison.Ordinal) || value.Contains("宸", StringComparison.Ordinal);
    }

    private static string Humanize(string id)
    {
        var words = id.Split('_', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
        return string.Join(" ", words.Select(word => char.ToUpperInvariant(word[0]) + word[1..]));
    }
}
