using System.Text.Json;

namespace ScadaLink.CLI;

public class CliConfig
{
    public string? ManagementUrl { get; set; }
    public string DefaultFormat { get; set; } = "json";

    public static CliConfig Load()
    {
        var config = new CliConfig();

        // Load from config file
        var configPath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
            ".scadalink", "config.json");
        if (File.Exists(configPath))
        {
            var json = File.ReadAllText(configPath);
            var fileConfig = JsonSerializer.Deserialize<CliConfigFile>(json,
                new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
            if (fileConfig != null)
            {
                if (!string.IsNullOrEmpty(fileConfig.ManagementUrl))
                    config.ManagementUrl = fileConfig.ManagementUrl;
                if (!string.IsNullOrEmpty(fileConfig.DefaultFormat))
                    config.DefaultFormat = fileConfig.DefaultFormat;
            }
        }

        // Override from environment variables
        var envUrl = Environment.GetEnvironmentVariable("SCADALINK_MANAGEMENT_URL");
        if (!string.IsNullOrEmpty(envUrl))
            config.ManagementUrl = envUrl;

        var envFormat = Environment.GetEnvironmentVariable("SCADALINK_FORMAT");
        if (!string.IsNullOrEmpty(envFormat))
            config.DefaultFormat = envFormat;

        return config;
    }

    private class CliConfigFile
    {
        public string? ManagementUrl { get; set; }
        public string? DefaultFormat { get; set; }
    }
}
