using Metin2Launcher.GameLaunch;
using Metin2Launcher.Runtime;
using Xunit;

namespace Metin2Launcher.Tests;

public class GameProcessTests
{
    [Fact]
    public void BuildStartInfo_matches_platform()
    {
        var exe = Path.Combine(Path.GetTempPath(), "Metin2.exe");
        var cwd = Path.GetTempPath();

        var psi = GameProcess.BuildStartInfo(exe, cwd);

        Assert.Equal(cwd, psi.WorkingDirectory);
        Assert.False(psi.UseShellExecute);

        if (OperatingSystem.IsLinux())
        {
            // Linux dev path must go through wine so the child inherits WINEPREFIX.
            Assert.Equal("wine", psi.FileName);
            Assert.Contains(exe, psi.ArgumentList);
        }
        else
        {
            // Windows / inside-Wine path: the file itself is the FileName.
            Assert.Equal(exe, psi.FileName);
            Assert.Empty(psi.ArgumentList);
        }
    }

    [Fact]
    public void BuildStartInfo_without_runtime_key_does_not_set_m2pack_env()
    {
        var exe = Path.Combine(Path.GetTempPath(), "Metin2.exe");
        var psi = GameProcess.BuildStartInfo(exe, Path.GetTempPath(), runtimeKey: null);
        Assert.False(psi.Environment.ContainsKey(EnvVarKeyDelivery.MasterKeyVar));
        Assert.False(psi.Environment.ContainsKey(EnvVarKeyDelivery.SignPubkeyVar));
        Assert.False(psi.Environment.ContainsKey(EnvVarKeyDelivery.KeyIdVar));
    }

    [Fact]
    public void BuildStartInfo_with_runtime_key_forwards_env_vars()
    {
        var exe = Path.Combine(Path.GetTempPath(), "Metin2.exe");
        var rk = new RuntimeKey
        {
            KeyId = "2026.04.14-1",
            MasterKeyHex = new string('a', 64),
            SignPubkeyHex = new string('b', 64),
        };
        var psi = GameProcess.BuildStartInfo(exe, Path.GetTempPath(), rk);
        Assert.Equal("2026.04.14-1", psi.Environment[EnvVarKeyDelivery.KeyIdVar]);
        Assert.Equal(new string('a', 64), psi.Environment[EnvVarKeyDelivery.MasterKeyVar]);
        Assert.Equal(new string('b', 64), psi.Environment[EnvVarKeyDelivery.SignPubkeyVar]);
    }

    [Fact]
    public void BuildStartInfo_runtime_key_does_not_pollute_current_process()
    {
        var exe = Path.Combine(Path.GetTempPath(), "Metin2.exe");
        var before = Environment.GetEnvironmentVariable(EnvVarKeyDelivery.MasterKeyVar);
        var rk = new RuntimeKey
        {
            KeyId = "k",
            MasterKeyHex = new string('c', 64),
            SignPubkeyHex = new string('d', 64),
        };
        GameProcess.BuildStartInfo(exe, Path.GetTempPath(), rk);
        var after = Environment.GetEnvironmentVariable(EnvVarKeyDelivery.MasterKeyVar);
        Assert.Equal(before, after);
    }
}
