using Nexus.Contracts.Apps;

namespace NexusShell.Services.Policy;

public static class NexusPolicyAppKeys
{
    public static string FromAppEntry(AppEntry app)
    {
        if (app.ExecutablePath.StartsWith("nexus:", StringComparison.OrdinalIgnoreCase))
        {
            var scheme = app.ExecutablePath.ToLowerInvariant();
            return scheme switch
            {
                "nexus:files" => "files",
                "nexus:browser" => "browser",
                "nexus:photos" => "photos",
                "nexus:media" => "media",
                "nexus:calculator" => "calculator",
                "nexus:settings" => "settings",
                "nexus:store" => "store",
                "nexus:devices" or "nexus:device-manager" => "device-manager",
                "nexus:console" => "console",
                "nexus:desktop" => "desktop",
                "nexus:hub" => "hub",
                "nexus:updates" => "settings",
                "nexus:diagnostics" => "settings",
                "nexus:placeholder" => "placeholder",
                _ => Normalize(app.Id),
            };
        }

        if (app.ExecutablePath.Contains("powershell", StringComparison.OrdinalIgnoreCase) ||
            app.ExecutablePath.Contains("cmd.exe", StringComparison.OrdinalIgnoreCase))
        {
            return "terminal";
        }

        if (app.ExecutablePath.Contains("explorer.exe", StringComparison.OrdinalIgnoreCase))
        {
            return "hub";
        }

        return Normalize(app.Id);
    }

    public static string FromPackageId(string packageId) =>
        packageId.StartsWith("nexus-", StringComparison.OrdinalIgnoreCase)
            ? packageId["nexus-".Length..]
            : Normalize(packageId);

    public static string FromDockLabel(string dockLabel) => dockLabel.ToLowerInvariant() switch
    {
        "files" => "files",
        "browser" => "browser",
        "terminal" or "console" => "console",
        "settings" => "settings",
        "calculator" => "calculator",
        "diagnostics" => "settings",
        "updates" => "settings",
        "store" => "store",
        "search" or "apps" or "app hub" or "nexus" or "nexus home" or "home" or "add" => "launcher",
        _ => Normalize(dockLabel),
    };

    private static string Normalize(string value) =>
        value.Replace("app-", "", StringComparison.OrdinalIgnoreCase)
            .Replace("nexus-", "", StringComparison.OrdinalIgnoreCase)
            .Replace('_', '-')
            .ToLowerInvariant();
}
