#include "directshow_control.h"

#ifdef _WIN32

#include <iostream>
#include <sstream>

// Temporary debug version that shows ALL cameras
std::vector<CameraDevice> DirectShowControl::discoverDevices() {
    std::vector<CameraDevice> devices;
    HRESULT hr = S_OK;
    CComPtr<ICreateDevEnum> pDevEnum;
    CComPtr<IEnumMoniker> pClassEnum;
    
    // Create the System Device Enumerator
    hr = pDevEnum.CoCreateInstance(CLSID_SystemDeviceEnum);
    if (FAILED(hr)) return devices;
    
    // Create an enumerator for video capture devices
    hr = pDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pClassEnum, 0);
    if (FAILED(hr)) return devices;
    
    CComPtr<IMoniker> pMoniker;
    int deviceIndex = 0;
    
    while (pClassEnum->Next(1, &pMoniker, nullptr) == S_OK) {
        CComPtr<IPropertyBag> pPropBag;
        hr = pMoniker->BindToStorage(0, 0, IID_PPV_ARGS(&pPropBag));
        if (SUCCEEDED(hr)) {
            VARIANT var;
            VariantInit(&var);
            
            // Get the friendly name
            hr = pPropBag->Read(L"FriendlyName", &var, 0);
            if (SUCCEEDED(hr)) {
                std::wstring wName = var.bstrVal;
                
                // DEBUG: Show ALL devices, not just Logitech
                CameraDevice device;
                
                // Convert wide string to string
                int len = WideCharToMultiByte(CP_UTF8, 0, wName.c_str(), -1, nullptr, 0, nullptr, nullptr);
                std::string name(len, 0);
                WideCharToMultiByte(CP_UTF8, 0, wName.c_str(), -1, &name[0], len, nullptr, nullptr);
                name.pop_back(); // Remove null terminator
                
                device.name = name;
                device.id = std::to_string(deviceIndex);
                device.vendorId = 0x0000; // Unknown for non-Logitech devices
                device.productId = 0x0000;
                
                // Check if this is a Logitech device and set proper IDs
                if (wName.find(L"Logitech") != std::wstring::npos) {
                    device.vendorId = 0x046d; // Logitech vendor ID
                    
                    if (wName.find(L"MX Brio") != std::wstring::npos) {
                        device.productId = 0x085e; // MX Brio product ID
                    } else if (wName.find(L"BRIO") != std::wstring::npos) {
                        device.productId = 0x085b; // BRIO 4K product ID
                    }
                }
                
                devices.push_back(device);
            }
            VariantClear(&var);
        }
        pMoniker.Release();
        deviceIndex++;
    }
    
    return devices;
}

#endif // _WIN32