using System.Diagnostics;
using ClaudeDo.Installer.Checks.Interfaces;
using ClaudeDo.Installer.Core.Interfaces;

namespace ClaudeDo.Installer.Checks;

public sealed class NetstatPortOwnerResolver : IPortOwnerResolver
{
    private readonly IProcessRunner _processRunner;

    public NetstatPortOwnerResolver(IProcessRunner processRunner) => _processRunner = processRunner;

    public async Task<string?> FindOwningProcessNameAsync(int port, CancellationToken ct)
    {
        var (exitCode, output) = await _processRunner.RunAsync("netstat.exe", "-ano -p TCP", null, ct);
        if (exitCode != 0) return null;

        var suffix = $":{port}";
        foreach (var line in output.Split('\n'))
        {
            var parts = line.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
            if (parts.Length < 5) continue;
            if (!parts[0].Equals("TCP", StringComparison.OrdinalIgnoreCase)) continue;
            if (!parts[1].EndsWith(suffix, StringComparison.Ordinal)) continue;
            if (!int.TryParse(parts[^1], out var pid)) continue;

            try { return Process.GetProcessById(pid).ProcessName; }
            catch { return null; }
        }

        return null;
    }
}
