using System.IO;
using System.Text;

namespace Noctalk_client.Client.Networking.Tor;

public static class Torrc_generator
{
    private static readonly UTF8Encoding Utf8_without_bom = new(false);

    public static void Torrc__generate__client(string The_executable_directory, int The_client_local_tor_port)
    {
        string torDirectory = Path.Combine(The_executable_directory, "darknet", "tor");
        string dataDirectory = Path.Combine(The_executable_directory, "darknet", "data");
        string torrcPath = Path.Combine(torDirectory, "torrc");
        string geoipPath = Path.Combine(torDirectory, "geoip");
        string geoip6Path = Path.Combine(torDirectory, "geoip6");

        Directory.CreateDirectory(torDirectory);
        Directory.CreateDirectory(dataDirectory);

        string torrc = string.Join(Environment.NewLine,
        [
            "# Noctalk_client generated torrc",
            string.Empty,
            $"DataDirectory {Torrc__quote_path(dataDirectory)}",
            string.Empty,
            "AvoidDiskWrites 1",
            "SafeLogging 1",
            "Log notice stdout",
            string.Empty,
            $"GeoIPFile {Torrc__quote_path(geoipPath)}",
            $"GeoIPv6File {Torrc__quote_path(geoip6Path)}",
            string.Empty,
            "ClientOnly 1",
            $"SocksPort 127.0.0.1:{The_client_local_tor_port}",
            string.Empty
        ]);

        File.WriteAllText(torrcPath, torrc, Utf8_without_bom);
    }

    private static string Torrc__quote_path(string The_path)
    {
        string escapedPath = Path.GetFullPath(The_path).Replace("\\", "\\\\");
        return $"\"{escapedPath}\"";
    }
}
