// Signal analysis utilities for spectrogram selection stats

#include "utils.h"

#include <math.h>
#include <stdlib.h>
#include <string.h>

SignalStats ComputeSignalStats(const AudioSignal* signal, int startSample, int endSample)
{
    SignalStats stats = {0};

    if (!signal || !signal->samples || endSample <= startSample ||
        startSample < 0 || endSample > signal->numSamples) {
        return stats;
    }

    int numSamples = endSample - startSample;
    float* samples = signal->samples + startSample;
    float peak = 0.0f;
    float energy = 0.0f;
    int peakIdx = 0;

    // Compute energy and find peak
    for (int i = 0; i < numSamples; i++) {
        float amp = samples[i];
        energy += amp * amp;
        if (fabsf(amp) > peak) {
            peak = fabsf(amp);
            peakIdx = i;
        }
    }

    stats.energy = energy;
    stats.peakAmplitude = peak;
    stats.rmsAmplitude = sqrtf(energy / numSamples);
    stats.durationSec = (float)numSamples / (float)signal->sampleRate;
    stats.peakSampleIdx = startSample + peakIdx;

    // PAPR in dB: 10 * log10(peak^2 / avg_power)
    // avg_power = energy / numSamples = rms^2
    // So PAPR = 10 * log10(peak^2 / rms^2) = 20 * log10(peak / rms)
    if (stats.rmsAmplitude > 0.0f) {
        stats.paprDb = 10.0f * log10f((peak * peak) / (stats.rmsAmplitude * stats.rmsAmplitude));
    } else {
        stats.paprDb = 0.0f;
    }

    return stats;
}
