using System.Diagnostics;

internal static class Directory
{
    internal static bool Exists(string path) => System.IO.Directory.Exists(path);
    internal static DirectoryInfo CreateDirectory(string path) => System.IO.Directory.CreateDirectory(path);
    internal static IEnumerable<string> EnumerateFileSystemEntries(string path) => System.IO.Directory.EnumerateFileSystemEntries(path);
    internal static void SetLastWriteTimeUtc(string path, DateTime value) => System.IO.Directory.SetLastWriteTimeUtc(path, value);
    internal static void Delete(string path) => System.IO.Directory.Delete(path);

    internal static DirectoryInfo CreateSymbolicLink(string path, string target)
    {
        try
        {
            var created = System.IO.Directory.CreateSymbolicLink(path, target);
            return new DirectoryInfo(created.FullName);
        }
        catch (UnauthorizedAccessException) { }
        catch (IOException ex) when ((ex.HResult & 0xFFFF) == 1314) { }

        var shell = Environment.GetEnvironmentVariable("ComSpec") ?? Path.Combine(Environment.SystemDirectory, "cmd.exe");
        var start = new ProcessStartInfo(shell)
        {
            UseShellExecute = false,
            CreateNoWindow = true,
            RedirectStandardOutput = true,
            RedirectStandardError = true
        };
        start.ArgumentList.Add("/d");
        start.ArgumentList.Add("/c");
        start.ArgumentList.Add("mklink");
        start.ArgumentList.Add("/J");
        start.ArgumentList.Add(path);
        start.ArgumentList.Add(target);
        using var process = Process.Start(start) ?? throw new IOException("Could not start junction fixture helper.");
        var stdout = process.StandardOutput.ReadToEnd();
        var stderr = process.StandardError.ReadToEnd();
        if (!process.WaitForExit(10_000) || process.ExitCode != 0)
            throw new IOException($"Could not create isolated junction fixture. Exit={process.ExitCode}; stdout={stdout}; stderr={stderr}");
        return new DirectoryInfo(path);
    }
}
