using System.Diagnostics;
using System.Threading;
using System;

public class ClientTelemetry
{
    private readonly Process _proc;

    public ClientTelemetry()
    {
        _proc = Process.GetCurrentProcess();
    }

    /// <summary>Working-set memory in bytes.</summary>
    public long MemoryBytes => _proc.WorkingSet64;

    /// <summary>Total open handles.</summary>
    public int HandleCount => _proc.HandleCount;

    /// <summary>CPU utilisation (%) averaged over <paramref name="sampleMs"/>.</summary>
    public float GetCpuUsage(int sampleMs = 500)
    {
        // you can keep your PerformanceCounter variant, but here’s a simpler PID-based way:
        var startCpu = _proc.TotalProcessorTime;
        var start = DateTime.UtcNow;
        Thread.Sleep(sampleMs);
        var endCpu = _proc.TotalProcessorTime;
        var end = DateTime.UtcNow;

        // CPU‐time used across all cores:
        var cpuMs = (endCpu - startCpu).TotalMilliseconds;
        var elapsedMs = (end - start).TotalMilliseconds * Environment.ProcessorCount;
        return (float)(cpuMs / elapsedMs * 100.0);
    }
}
