using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ModpackLauncher.Services;

/// <summary>
/// Pre-seeds Iris's <c>config/iris.properties</c> with a default shader pack
/// for fresh installs, so friends launch the game and the recommended shader
/// is already on rather than them having to dig through Video Settings.
///
/// Respects user choice: if the file already exists with a non-empty
/// <c>shaderPack=...</c> entry, we leave it alone -- only fresh installs (or
/// installs where Iris has never been opened) get the default.
/// </summary>
public sealed class IrisConfigService
{
    public void SetDefaultShader(string gameDir, string shaderPackFilename)
    {
        if (string.IsNullOrWhiteSpace(shaderPackFilename)) return;
        var configDir = Path.Combine(gameDir, "config");
        Directory.CreateDirectory(configDir);
        var path = Path.Combine(configDir, "iris.properties");

        var lines = File.Exists(path) ? File.ReadAllLines(path).ToList() : new List<string>();

        // If a shaderPack is already chosen and non-empty (the user picked
        // something), respect it and bail.
        var existingShader = lines
            .Select(l => l.TrimStart())
            .Where(l => l.Length > 0 && l[0] != '#')
            .Select(l => { var i = l.IndexOf('='); return i < 0 ? null : new { Key = l.Substring(0, i).Trim(), Value = l.Substring(i + 1).Trim() }; })
            .Where(p => p != null && p.Key.Equals("shaderPack", System.StringComparison.OrdinalIgnoreCase))
            .Select(p => p!.Value)
            .FirstOrDefault();
        if (!string.IsNullOrEmpty(existingShader)) return;

        // No shader set -- write our defaults. Update existing keys in-place if
        // they exist (e.g. shaderPack="" placeholder), append otherwise.
        var defaults = new Dictionary<string, string>(System.StringComparer.OrdinalIgnoreCase)
        {
            { "shaderPack", shaderPackFilename },
            { "enableShaders", "true" },
        };
        var seen = new HashSet<string>(System.StringComparer.OrdinalIgnoreCase);
        for (int i = 0; i < lines.Count; i++)
        {
            var trimmed = lines[i].TrimStart();
            if (trimmed.Length == 0 || trimmed[0] == '#') continue;
            var idx = trimmed.IndexOf('=');
            if (idx < 0) continue;
            var key = trimmed.Substring(0, idx).Trim();
            if (defaults.TryGetValue(key, out var val))
            {
                lines[i] = $"{key}={val}";
                seen.Add(key);
            }
        }
        foreach (var (k, v) in defaults)
        {
            if (!seen.Contains(k)) lines.Add($"{k}={v}");
        }
        File.WriteAllLines(path, lines);
    }
}
