namespace ClaudeDo.Ui.Services;

public sealed class InstallerLocator
{
    private const string InstallJson = "install.json";
    private const string InstallerExe = "ClaudeDo.Installer.exe";
    private const string UninstallerSubdir = "uninstaller";

    public string? Find()
        => FindByWalkingUp(AppContext.BaseDirectory)
           ?? (OperatingSystem.IsWindows() ? FindByRegistry() : null);

    public string? FindByWalkingUp(string startDir)
    {
        var dir = new DirectoryInfo(startDir);
        while (dir is not null)
        {
            var manifest = Path.Combine(dir.FullName, InstallJson);
            if (File.Exists(manifest))
            {
                var candidate = Path.Combine(dir.FullName, UninstallerSubdir, InstallerExe);
                return File.Exists(candidate) ? candidate : null;
            }
            dir = dir.Parent;
        }
        return null;
    }

    [System.Runtime.Versioning.SupportedOSPlatform("windows")]
    public string? FindByRegistry()
    {
        if (!OperatingSystem.IsWindows()) return null;

        try
        {
            using var key = Microsoft.Win32.Registry.LocalMachine
                .OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\ClaudeDo");
            var location = key?.GetValue("InstallLocation") as string;
            if (string.IsNullOrEmpty(location)) return null;
            var candidate = Path.Combine(location, UninstallerSubdir, InstallerExe);
            return File.Exists(candidate) ? candidate : null;
        }
        catch
        {
            return null;
        }
    }
}
