"""Patches deltacast-bridge audio_thread to follow SDK Sample_RXAudio.cpp:
- Set Mode/BufferFormat on BOTH pAudioChannels[0] AND [1] (stereo pair)
- Get/Set VHD_SDI_SP_INTERFACE on the audio stream
Without these, VHD_SlotExtractAudio returns 0 samples (silent capture)."""
path = 'services/capture/deltacast-bridge/main.c'
with open(path) as f:
    s = f.read()

old = """    ULONG r = VHD_OpenStreamHandle(ps->board, rx_streamtype(ps->port),
                                   VHD_SDI_STPROC_DISJOINED_ANC,
                                   NULL, &stream, NULL);
    if (r == VHDERR_NOERROR) {
        VHD_SetStreamProperty(stream, VHD_SDI_SP_VIDEO_STANDARD,    ps->video_std);
        VHD_SetStreamProperty(stream, VHD_SDI_SP_CLOCK_SYSTEM,      ps->clock_div);
        VHD_SetStreamProperty(stream, VHD_CORE_SP_TRANSFER_SCHEME,  VHD_TRANSFER_SLAVED);

        ai.pAudioGroups[0].pAudioChannels[0].Mode         = VHD_AM_STEREO;
        ai.pAudioGroups[0].pAudioChannels[0].BufferFormat = VHD_AF_16;
        ai.pAudioGroups[0].pAudioChannels[0].pData        = buf;"""

new = """    ULONG r = VHD_OpenStreamHandle(ps->board, rx_streamtype(ps->port),
                                   VHD_SDI_STPROC_DISJOINED_ANC,
                                   NULL, &stream, NULL);
    if (r == VHDERR_NOERROR) {
        /* Per Deltacast SDK Sample_RXAudio.cpp: VHD_SDI_SP_INTERFACE must be
         * propagated to the audio stream, otherwise VHD_SlotExtractAudio
         * returns 0 samples (silent capture). */
        ULONG iface = 0;
        VHD_GetStreamProperty(stream, VHD_SDI_SP_INTERFACE, &iface);

        VHD_SetStreamProperty(stream, VHD_SDI_SP_VIDEO_STANDARD,    ps->video_std);
        VHD_SetStreamProperty(stream, VHD_SDI_SP_CLOCK_SYSTEM,      ps->clock_div);
        VHD_SetStreamProperty(stream, VHD_CORE_SP_TRANSFER_SCHEME,  VHD_TRANSFER_SLAVED);
        VHD_SetStreamProperty(stream, VHD_SDI_SP_INTERFACE,         iface);

        /* Configure BOTH channels of the stereo pair (group 0). The actual PCM
         * samples land in pAudioChannels[0].pData (packed L/R s16le). Channel
         * [1] must declare Mode+BufferFormat so the SDK recognizes the pair. */
        ai.pAudioGroups[0].pAudioChannels[0].Mode         = VHD_AM_STEREO;
        ai.pAudioGroups[0].pAudioChannels[0].BufferFormat = VHD_AF_16;
        ai.pAudioGroups[0].pAudioChannels[0].pData        = buf;
        ai.pAudioGroups[0].pAudioChannels[1].Mode         = VHD_AM_STEREO;
        ai.pAudioGroups[0].pAudioChannels[1].BufferFormat = VHD_AF_16;"""

assert old in s, 'Old block not found'
s = s.replace(old, new, 1)
with open(path, 'w') as f:
    f.write(s)
print('PATCHED OK')
