using HidSharp;
using System.Text;
using System.Windows;

// Keychron K8 (?)
const ushort TargetVID = 0x05AC;
const ushort TargetPID = 0x024F;

// Framework Laptop keyboard
// const ushort TargetVID = 0x32AC;
// const ushort TargetPID = 0x0012;

StringBuilder buffer = new();
string line = "";

foreach (var hidDevice in DeviceList.Local.GetHidDevices())
{
    var vid = hidDevice.VendorID;
    var pid = hidDevice.ProductID;

    Console.WriteLine($"Trying device VID = {vid:X4} & PID = {pid:X4}");

    if (vid != TargetVID || pid != TargetPID)
    {
        continue;
    }

    try
    {
        WriteLine($"DevicePath = ${hidDevice.DevicePath}");

        // var report = hidDevice.GetReportDescriptor();
        var report = hidDevice.GetRawReportDescriptor();
        if (report == null)
        {
            WriteLine($"Report is null");
            continue;
        }

        WriteLine($"Report = [ {string.Join(", ", report.Select(b => string.Format("{0:X2}", b)))} ]");

        ushort usagePage = (ushort)(report[2] << 8 | report[1]);
        byte usage = report[4];

        WriteLine($"Usage = {usage:X2}");
        WriteLine($"UsagePage = {usagePage:X4}");
        WriteLine("");
    }
    catch (Exception e)
    {
        WriteLine($"Error: {e}");
    }
}

Clipboard.SetText(buffer.ToString());

Console.WriteLine("Press Enter to close");
Console.ReadLine();

void WriteLine(string str)
{
    buffer.AppendLine(line);
    Console.WriteLine(line);
}
