using System.Text.RegularExpressions;
using YMhut.Box.Core;

namespace YMhut.Box.Core.Logging;

public static class LogDisplayLocalizer
{
    public static string Level(string? level, string language = "zh-CN")
    {
        var english = English(language);
        return level?.Trim() switch
        {
            "Trace" => english ? "Trace" : "跟踪",
            "Debug" => english ? "Debug" : "调试",
            "Information" => english ? "Info" : "信息",
            "Warning" => english ? "Warning" : "警告",
            "Error" => english ? "Error" : "错误",
            "Critical" => english ? "Critical" : "严重",
            _ => english ? "Info" : "信息"
        };
    }

    public static string Category(string? category, string language = "zh-CN")
    {
        var english = English(language);
        return (category ?? string.Empty).Trim().ToLowerInvariant() switch
        {
            "navigation" => english ? "Navigation" : "导航",
            "tool" => english ? "Tool" : "工具",
            "network" => english ? "Network" : "网络",
            "api" => english ? "API" : "接口",
            "solar" => english ? "Solar system" : "太阳系",
            "service" => english ? "Service" : "服务",
            "about" => english ? "About" : "关于",
            "download" => english ? "Download" : "下载",
            "risk" => english ? "Risk" : "风险确认",
            "dev-env" => english ? "Development environment" : "开发环境",
            "tool-run" => english ? "Tool run" : "工具运行",
            "builtin-tool" => english ? "Built-in tool" : "内置工具",
            "tool-result" => english ? "Tool result" : "工具结果",
            "tool-metadata" => english ? "Tool metadata" : "工具元数据",
            "plugin" => english ? "Plugin" : "插件",
            "plugin-host" => english ? "Plugin host" : "插件宿主",
            "update" => english ? "Update" : "更新",
            "settings" => english ? "Settings" : "设置",
            "feedback" => english ? "Feedback" : "反馈",
            "safe_browser" => english ? "Safe browser" : "安全浏览器",
            "media_player" => english ? "Media player" : "媒体播放器",
            "window" => english ? "Window" : "窗口",
            "system" => english ? "System" : "系统",
            "startup" => english ? "Startup" : "启动",
            "startup-check" => english ? "Startup check" : "启动自检",
            "version" => english ? "Version" : "版本",
            "worker" => english ? "Worker" : "工具进程",
            "" => english ? "General" : "通用",
            var value => Humanize(value)
        };
    }

    public static string Message(string? message, string language = "zh-CN")
    {
        var text = SensitiveText.Sanitize(message, 260);
        var english = English(language);
        var normalized = text.Trim();
        var exact = normalized.ToLowerInvariant() switch
        {
            "open home page" => english ? "Open home page" : "打开首页",
            "open toolbox" => english ? "Open toolbox" : "打开工具箱",
            "open logs" => english ? "Open logs" : "打开日志",
            "open service status" => english ? "Open service status" : "打开服务状态",
            "open startup check results" => english ? "Open startup check results" : "打开启动自检结果",
            "open download manager" => english ? "Open download manager" : "打开下载管理",
            "open plugin docs" => english ? "Open plugin docs" : "打开插件文档",
            "open settings" => english ? "Open settings" : "打开设置",
            "open about" => english ? "Open about" : "打开关于",
            "open plugins" => english ? "Open plugins" : "打开插件页",
            "open feedback" => english ? "Open feedback" : "打开反馈",
            "tool catalog rebuilt" => english ? "Tool catalog rebuilt" : "工具目录已重建",
            "external tools scanned" => english ? "External tools scanned" : "外部工具已扫描",
            "user launched downloaded installer" => english ? "User launched downloaded installer" : "用户打开已下载的安装包",
            "external tool icon extracted" => english ? "External tool icon extracted" : "已提取外部工具图标",
            "tool worker process started" => english ? "Tool worker process started" : "工具工作进程已启动",
            "tool worker ready" => english ? "Tool worker ready" : "工具工作进程已就绪",
            "tool worker unavailable; using in-process fallback" => english ? "Tool worker unavailable; using in-process fallback" : "工具工作进程不可用，已改用进程内执行",
            "tool worker execution failed" => english ? "Tool worker execution failed" : "工具工作进程执行失败",
            "download host process started" => english ? "Download host process started" : "下载宿主进程已启动",
            "download host read loop stopped" => english ? "Download host read loop stopped" : "下载宿主读取循环已停止",
            "download started" => english ? "Download started" : "下载已开始",
            "download completed" => english ? "Download completed" : "下载已完成",
            "download completed and verified" => english ? "Download completed and verified" : "下载已完成并通过校验",
            "installer package cleaned" => english ? "Installer package cleaned" : "安装包已清理",
            "installer cleanup failed" => english ? "Installer cleanup failed" : "安装包清理失败",
            "open source references loaded" => english ? "Open source references loaded" : "开源引用已加载",
            "open source reference scan degraded" => english ? "Open source reference scan degraded" : "开源引用扫描已降级",
            "external tool metadata load failed" => english ? "External tool metadata load failed" : "外部工具元数据加载失败",
            "startup check found missing critical files or language resources. please reinstall with the latest setup package." => english ? "Startup check found missing critical files or language resources. Please reinstall with the latest setup package." : "启动自检发现关键文件或语言资源缺失，请使用最新安装包重新安装。",
            "toolbox layout changed" => english ? "Toolbox layout changed" : "工具箱布局已更改",
            "toolbox default scope changed" => english ? "Toolbox default scope changed" : "工具箱默认范围已更改",
            "toolbox compact cards changed" => english ? "Toolbox compact cards changed" : "工具箱紧凑卡片设置已更改",
            "toolbox recent-first changed" => english ? "Toolbox recent-first changed" : "工具箱最近优先设置已更改",
            "hardware brand logo setting changed" => english ? "Hardware brand logo setting changed" : "硬件品牌标识设置已更改",
            "risk confirmation setting changed" => english ? "Risk confirmation setting changed" : "风险确认设置已更改",
            "risk confirmation reset cancelled" => english ? "Risk confirmation reset cancelled" : "风险确认重置已取消",
            "risk confirmations reset from settings" => english ? "Risk confirmations reset from settings" : "已从设置重置风险确认",
            "builtin tool execution cancelled" => english ? "Built-in tool execution cancelled" : "已取消内置工具执行",
            "external tool launch cancelled" => english ? "External tool launch cancelled" : "已取消外部工具启动",
            "builtin tool risk confirmed" => english ? "Built-in tool risk confirmed" : "已确认内置工具风险",
            "external tool risk confirmed" => english ? "External tool risk confirmed" : "已确认外部工具风险",
            "plugin validation failed" => english ? "Plugin validation failed" : "插件校验失败",
            "plugin surface opened" => english ? "Plugin surface opened" : "插件页面已打开",
            "plugin surface opened in window" => english ? "Plugin surface opened in window" : "插件窗口已打开",
            "plugin host failed" => english ? "Plugin host failed" : "插件宿主异常",
            "plugin window failed" => english ? "Plugin window failed" : "插件窗口异常",
            "load plugin snapshot failed" => english ? "Failed to load plugin snapshot" : "插件快照加载失败",
            "reload plugin catalog failed" => english ? "Failed to reload plugin catalog" : "插件目录刷新失败",
            "plugin host ready" => english ? "Plugin host ready" : "插件宿主已就绪",
            "plugin host process started" => english ? "Plugin host process started" : "插件宿主进程已启动",
            "plugin host request timed out" => english ? "Plugin host request timed out" : "插件宿主请求超时",
            "plugin host request failed" => english ? "Plugin host request failed" : "插件宿主请求失败",
            "plugin host pipe failed" => english ? "Plugin host pipe failed" : "插件宿主管道异常",
            "plugin background refresh failed" => english ? "Plugin background refresh failed" : "插件后台刷新失败",
            "plugin watcher failed" => english ? "Plugin watcher failed" : "插件目录监听失败",
            "plugin hot reload" => english ? "Plugin hot reload" : "插件热刷新",
            "plugin hot reload failed" => english ? "Plugin hot reload failed" : "插件热刷新失败",
            "plugin scan failed" => english ? "Plugin scan failed" : "插件扫描失败",
            "plugin host failed to start" => english ? "Plugin host failed to start" : "插件宿主启动失败",
            "plugin http fetch" => english ? "Plugin HTTP fetch" : "插件 HTTP 请求",
            "plugin ran built-in tool" => english ? "Plugin ran built-in tool" : "插件调用了内置工具",
            "feedback sent" => english ? "Feedback sent" : "反馈已发送",
            "feedback send failed" => english ? "Feedback send failed" : "反馈发送失败",
            "update check failed" => english ? "Update check failed" : "检查更新失败",
            "update notice check failed" => english ? "Update notice check failed" : "\u66f4\u65b0\u901a\u77e5\u68c0\u67e5\u5931\u8d25",
            "service status check completed" => english ? "Service status check completed" : "\u670d\u52a1\u72b6\u6001\u68c0\u67e5\u5b8c\u6210",
            "install integrity check completed" => english ? "Install integrity check completed" : "\u5b89\u88c5\u5b8c\u6574\u6027\u68c0\u67e5\u5b8c\u6210",
            "install integrity check failed" => english ? "Install integrity check failed" : "\u5b89\u88c5\u5b8c\u6574\u6027\u68c0\u67e5\u5931\u8d25",
            "monthly install integrity check failed" => english ? "Monthly install integrity check failed" : "\u6708\u5ea6\u5b89\u88c5\u5b8c\u6574\u6027\u68c0\u67e5\u5931\u8d25",
            "startup check result preload failed" => english ? "Startup check result preload failed" : "\u542f\u52a8\u81ea\u68c0\u7ed3\u679c\u9884\u52a0\u8f7d\u5931\u8d25",
            "startup check report load failed" => english ? "Startup check report load failed" : "\u542f\u52a8\u81ea\u68c0\u62a5\u544a\u8bfb\u53d6\u5931\u8d25",
            "settings page initialized" => english ? "Settings page initialized" : "\u8bbe\u7f6e\u9875\u5df2\u521d\u59cb\u5316",
            "settings page load failed" => english ? "Settings page load failed" : "\u8bbe\u7f6e\u9875\u52a0\u8f7d\u5931\u8d25",
            "close confirmation remembered" => english ? "Close confirmation remembered" : "\u5df2\u8bb0\u4f4f\u5173\u95ed\u786e\u8ba4\u9009\u62e9",
            "window close requested" => english ? "Window close requested" : "\u7528\u6237\u8bf7\u6c42\u5173\u95ed\u7a97\u53e3",
            "window close cancelled" => english ? "Window close cancelled" : "\u5df2\u53d6\u6d88\u5173\u95ed\u7a97\u53e3",
            "window minimized to tray" => english ? "Window minimized to tray" : "\u7a97\u53e3\u5df2\u6700\u5c0f\u5316\u5230\u6258\u76d8",
            "proxy diagnostic failed" => english ? "Proxy diagnostic failed" : "代理诊断失败",
            _ => string.Empty
        };
        if (!string.IsNullOrEmpty(exact))
        {
            return exact;
        }

        var toolMatch = Regex.Match(normalized, @"^Open tool:\s*(?<tool>.+)$", RegexOptions.IgnoreCase);
        if (toolMatch.Success)
        {
            return english ? $"Open tool: {toolMatch.Groups["tool"].Value}" : $"打开工具：{toolMatch.Groups["tool"].Value}";
        }

        var externalToolMatch = Regex.Match(normalized, @"^Open external tool:\s*(?<tool>.+)$", RegexOptions.IgnoreCase);
        if (externalToolMatch.Success)
        {
            return english ? $"Open external tool: {externalToolMatch.Groups["tool"].Value}" : $"打开外部工具：{externalToolMatch.Groups["tool"].Value}";
        }

        var builtinToolMatch = Regex.Match(normalized, @"^Open built-in reference tool:\s*(?<tool>.+)$", RegexOptions.IgnoreCase);
        if (builtinToolMatch.Success)
        {
            return english ? $"Open built-in reference tool: {builtinToolMatch.Groups["tool"].Value}" : $"打开内置工具：{builtinToolMatch.Groups["tool"].Value}";
        }

        var workerQueueMatch = Regex.Match(normalized, @"^Queued tool in worker:\s*(?<tool>.+)$", RegexOptions.IgnoreCase);
        if (workerQueueMatch.Success)
        {
            return english ? $"Queued tool in worker: {workerQueueMatch.Groups["tool"].Value}" : $"工具已加入工作进程队列：{workerQueueMatch.Groups["tool"].Value}";
        }

        var workerExecuteMatch = Regex.Match(normalized, @"^Executing tool:\s*(?<tool>.+)$", RegexOptions.IgnoreCase);
        if (workerExecuteMatch.Success)
        {
            return english ? $"Executing tool: {workerExecuteMatch.Groups["tool"].Value}" : $"正在执行工具：{workerExecuteMatch.Groups["tool"].Value}";
        }

        var pluginSurfaceMatch = Regex.Match(normalized, @"^Open plugin surface:\s*(?<surface>.+)$", RegexOptions.IgnoreCase);
        if (pluginSurfaceMatch.Success)
        {
            return english ? $"Open plugin surface: {pluginSurfaceMatch.Groups["surface"].Value}" : $"打开插件页面：{pluginSurfaceMatch.Groups["surface"].Value}";
        }

        var externalRunMatch = Regex.Match(normalized, @"^External tool (?<result>success|failed|canceled|cancelled|timeout)(?::\s*(?<operation>.+))?$", RegexOptions.IgnoreCase);
        if (externalRunMatch.Success)
        {
            var result = ResultText(externalRunMatch.Groups["result"].Value, english);
            var operationValue = externalRunMatch.Groups["operation"].Value;
            if (string.IsNullOrWhiteSpace(operationValue))
            {
                return english ? $"External tool {result}" : $"外部工具{result}";
            }

            var operation = OperationText(operationValue, english);
            return english ? $"External tool {result}: {operation}" : $"外部工具{result}：{operation}";
        }

        var builtinRunMatch = Regex.Match(normalized, @"^Builtin tool (?<result>success|failed|canceled|cancelled|timeout)(?::\s*(?<tool>.+))?$", RegexOptions.IgnoreCase);
        if (builtinRunMatch.Success)
        {
            var result = ResultText(builtinRunMatch.Groups["result"].Value, english);
            if (string.IsNullOrWhiteSpace(builtinRunMatch.Groups["tool"].Value))
            {
                return english ? $"Built-in tool {result}" : $"内置工具{result}";
            }

            return english ? $"Built-in tool {result}: {builtinRunMatch.Groups["tool"].Value}" : $"内置工具{result}：{builtinRunMatch.Groups["tool"].Value}";
        }

        var toolResultMatch = Regex.Match(normalized, @"^Tool result (?<result>[^:]+):\s*(?<operation>.+)$", RegexOptions.IgnoreCase);
        if (toolResultMatch.Success)
        {
            var result = ResultText(toolResultMatch.Groups["result"].Value, english);
            var operation = OperationText(toolResultMatch.Groups["operation"].Value, english);
            return english ? $"Tool result {result}: {operation}" : $"工具结果{result}：{operation}";
        }

        var detectMatch = Regex.Match(normalized, @"^Detect (?<id>.+) failed$", RegexOptions.IgnoreCase);
        if (detectMatch.Success)
        {
            return english ? $"Detect {detectMatch.Groups["id"].Value} failed" : $"检测失败：{detectMatch.Groups["id"].Value}";
        }

        var fetchVersionsMatch = Regex.Match(normalized, @"^Fetch versions failed:\s*(?<id>.+)$", RegexOptions.IgnoreCase);
        if (fetchVersionsMatch.Success)
        {
            return english ? $"Fetch versions failed: {fetchVersionsMatch.Groups["id"].Value}" : $"获取版本失败：{fetchVersionsMatch.Groups["id"].Value}";
        }

        var startupMissingMatch = Regex.Match(normalized, @"^Startup check found (?<count>\d+) critical missing items\. Open Service status for details\.$", RegexOptions.IgnoreCase);
        if (startupMissingMatch.Success)
        {
            return english
                ? $"Startup check found {startupMissingMatch.Groups["count"].Value} critical missing items. Open Service status for details."
                : $"启动自检发现 {startupMissingMatch.Groups["count"].Value} 个关键缺失项，请在服务状态中查看详情。";
        }

        var navigationMatch = Regex.Match(normalized, @"^Navigation failed:\s*(?<page>.+)$", RegexOptions.IgnoreCase);
        if (navigationMatch.Success)
        {
            return english ? $"Navigation failed: {navigationMatch.Groups["page"].Value}" : $"页面打开失败：{navigationMatch.Groups["page"].Value}";
        }

        var genericOpenMatch = Regex.Match(normalized, @"^Open\s+(?<target>.+)$", RegexOptions.IgnoreCase);
        if (genericOpenMatch.Success)
        {
            return english ? $"Open {genericOpenMatch.Groups["target"].Value}" : $"打开 {genericOpenMatch.Groups["target"].Value}";
        }

        return text;
    }

    public static string Detail(string? detail, string language = "zh-CN", int maxLength = 600)
    {
        if (string.IsNullOrWhiteSpace(detail))
        {
            return English(language) ? "No details" : "暂无详情";
        }

        var safe = SensitiveText.Sanitize(detail, maxLength);
        if (English(language))
        {
            return safe;
        }

        return LocalizeDetailPayload(safe);
    }

    private static bool English(string? language) => string.Equals(language, "en-US", StringComparison.OrdinalIgnoreCase);

    private static string LocalizeDetailPayload(string detail)
    {
        var result = detail;
        foreach (var (source, target) in new (string Source, string Target)[]
        {
            ("result=success", "结果=成功"),
            ("result=failed", "结果=失败"),
            ("result=canceled", "结果=已取消"),
            ("operation=launch-admin", "操作=管理员启动"),
            ("operation=launch", "操作=启动"),
            ("operation=open-directory", "操作=打开目录"),
            ("operation=execute", "操作=执行"),
            ("operation=render", "操作=渲染"),
            ("operation=export", "操作=导出"),
            ("elapsedMs=", "耗时毫秒="),
            ("durationMs=", "耗时毫秒="),
            ("chars=", "字符数="),
            ("blocks=", "结果块="),
            ("error=", "错误="),
            ("detail=", "详情="),
            ("toolId=", "工具="),
            ("root=", "根目录="),
            ("count=", "数量="),
            ("toolNotices=", "工具声明数="),
            ("source=tray", "来源=托盘"),
            ("behavior=exit_directly", "行为=直接退出"),
            ("behavior=minimize_to_tray", "行为=最小化到托盘"),
            ("behavior=ask", "行为=询问"),
            ("dialog=com_exception", "弹窗=COM 异常"),
            ("result=primary", "结果=主按钮"),
            ("result=secondary", "结果=次按钮"),
            ("result=cancel", "结果=取消"),
            ("mode=", "模式="),
            ("scope=", "范围="),
            ("source=", "来源="),
            ("behavior=", "行为="),
            ("dialog=", "弹窗="),
            ("native=", "原生工具="),
            ("builtin=", "内置工具="),
            ("external=", "外部工具="),
            ("plugin=", "插件="),
            ("language=", "语言="),
            ("enabled=True", "已启用=是"),
            ("enabled=False", "已启用=否"),
            ("enabled=true", "已启用=是"),
            ("enabled=false", "已启用=否"),
            ("remembered=True", "已记住=是"),
            ("remembered=False", "已记住=否"),
            ("remembered=true", "已记住=是"),
            ("remembered=false", "已记住=否")
        })
        {
            result = result.Replace(source, target, StringComparison.OrdinalIgnoreCase);
        }

        return result;
    }

    private static string ResultText(string value, bool english)
    {
        return value.Trim().ToLowerInvariant() switch
        {
            "success" => english ? "success" : "成功",
            "failed" => english ? "failed" : "失败",
            "canceled" or "cancelled" => english ? "canceled" : "已取消",
            "timeout" => english ? "timeout" : "超时",
            var other => english ? other : other
        };
    }

    private static string OperationText(string value, bool english)
    {
        return value.Trim().ToLowerInvariant() switch
        {
            "launch" => english ? "launch" : "启动",
            "launch-admin" => english ? "launch as administrator" : "管理员启动",
            "open-directory" => english ? "open directory" : "打开目录",
            "execute" => english ? "execute" : "执行",
            "render" => english ? "render" : "渲染",
            "export" => english ? "export" : "导出",
            var other => english ? other : other
        };
    }

    private static string Humanize(string value)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            return value;
        }

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