using k8s;
using Microsoft.Extensions.Configuration;

namespace LazyBear.MCP.Services.Kubernetes;

public static class K8sClientFactory
{
    public static IKubernetes CreateClient(IConfiguration configuration)
    {
        var kubeconfigPath = configuration["Kubernetes:KubeconfigPath"];
        KubernetesClientConfiguration clientConfiguration;

        if (!string.IsNullOrWhiteSpace(kubeconfigPath))
        {
            var expandedPath = Environment.ExpandEnvironmentVariables(kubeconfigPath);
            var fullPath = Path.GetFullPath(expandedPath);

            clientConfiguration = KubernetesClientConfiguration.BuildConfigFromConfigFile(fullPath);
            return new global::k8s.Kubernetes(clientConfiguration);
        }

        try
        {
            clientConfiguration = KubernetesClientConfiguration.BuildConfigFromConfigFile();
        }
        catch
        {
            clientConfiguration = KubernetesClientConfiguration.InClusterConfig();
        }

        return new global::k8s.Kubernetes(clientConfiguration);
    }
}
