namespace HanaTui.Hana;

/// <summary>
/// Locates the SAP HANA client binaries (hdbsql, hdbuserstore) on the system.
/// Mirrors the path detection logic from keymanager.sh.
/// </summary>
public static class HdbClientLocator
{
    private static readonly string[] KnownPaths =
    [
        "/usr/sap/hdbclient",
        "/usr/sap/NDB/HDB00/exe",
    ];

    private static string? _resolvedPath;

    /// <summary>
    /// Returns the full path to hdbsql, or just "hdbsql" if it's on PATH.
    /// Throws if the client cannot be found anywhere.
    /// </summary>
    public static string HdbSql => Resolve("hdbsql");

    /// <summary>
    /// Returns the full path to hdbuserstore, or just "hdbuserstore" if it's on PATH.
    /// </summary>
    public static string HdbUserstore => Resolve("hdbuserstore");

    /// <summary>
    /// Returns the resolved client directory, or null if only found via PATH.
    /// </summary>
    public static string? ClientDirectory => GetClientDirectory();

    private static string Resolve(string binary)
    {
        var dir = GetClientDirectory();
        if (dir is not null)
            return Path.Combine(dir, binary);

        // Fall back to PATH — let the OS resolve it
        return binary;
    }

    private static string? GetClientDirectory()
    {
        if (_resolvedPath is not null)
            return _resolvedPath;

        foreach (var path in KnownPaths)
        {
            if (Directory.Exists(path))
            {
                _resolvedPath = path;
                return _resolvedPath;
            }
        }

        // Not found in known paths — return null (caller will use PATH)
        return null;
    }

    /// <summary>
    /// Checks whether hdbsql is available either in a known path or on PATH.
    /// </summary>
    public static bool IsAvailable()
    {
        if (GetClientDirectory() is not null)
            return true;

        // Check if it's available on PATH by attempting to locate it
        var pathEnv = Environment.GetEnvironmentVariable("PATH") ?? "";
        foreach (var dir in pathEnv.Split(':'))
        {
            if (File.Exists(Path.Combine(dir, "hdbsql")))
                return true;
        }

        return false;
    }
}
