using Sdt.Config;

namespace Sdt.Core;

internal static class LegacyScriptRequirementResolver
{
    public static List<ToolRequirement> InferForPowerShellArgs(IReadOnlyList<string> args)
    {
        var script = FindScriptArg(args);
        if (string.IsNullOrWhiteSpace(script))
            return [];

        static ToolRequirement Req(string tool) => new() { Tool = tool, InstallPolicy = InstallPolicy.Prompt };

        var file = Path.GetFileName(script).ToLowerInvariant();
        var lowerArgs = args.Select(a => a.ToLowerInvariant()).ToList();

        return file switch
        {
            "publish-app.ps1" => IsTauriTarget(lowerArgs)
                ? [Req("python"), Req("node"), Req("npm"), Req("cargo")]
                : [Req("python"), Req("node"), Req("npm")],
            "publish-sidecar.ps1" => [Req("python"), Req("dotnet")],
            "publish-webgateway.ps1" => [Req("python"), Req("dotnet"), Req("node"), Req("npm")],
            "run-webgateway.ps1" => [Req("python"), Req("dotnet")],
            "migration-gate.ps1" => [Req("python"), Req("dotnet")],
            "nuget-export-cache.ps1" => [Req("python"), Req("dotnet")],
            "nuget-import-cache.ps1" => [Req("python"), Req("dotnet")],
            "npm-clean.ps1" => [Req("python"), Req("node"), Req("npm")],
            "publish-output.ps1" => [Req("python"), Req("dotnet"), Req("node"), Req("npm"), Req("cargo")],
            "sync-output.ps1" => [Req("python")],
            "dotnet-min.ps1" => [Req("python"), Req("dotnet")],
            "pip-min.ps1" => [Req("python")],
            _ => [Req("python")]
        };
    }

    private static string? FindScriptArg(IReadOnlyList<string> args)
    {
        for (var i = 0; i < args.Count - 1; i++)
        {
            if (string.Equals(args[i], "-File", StringComparison.OrdinalIgnoreCase))
                return args[i + 1];
        }

        return args.FirstOrDefault(a => a.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase));
    }

    private static bool IsTauriTarget(IReadOnlyList<string> lowerArgs)
    {
        for (var i = 0; i < lowerArgs.Count - 1; i++)
        {
            if (lowerArgs[i] is "-target" or "--target" && lowerArgs[i + 1] == "tauri")
                return true;
        }

        return false;
    }
}
