// stft.h - STFT computation, adaptive resolution, and the FFT-size LRU cache
#ifndef STFT_H
#define STFT_H

#include "spectrogram_types.h"

// --- STFT computation ---
void ComputeSTFTInit(AudioSignal* signal, StftResult* result, int fftSize);
bool ComputeSTFTIncremental(AudioSignal* signal, StftResult* result, int fftSize, int startSegment);
int  ComputeNextHighResChunk(AudioSignal* signal, StftResult* result, int fftSize, int startSeg, int endSeg);
void FreeSTFT(StftResult* result);

// --- Adaptive resolution & display scaling ---
int  ComputeSkipFactor(float signalDurationSec);
void AutoScaleAmplitude(StftResult* stft);

// --- Spectral measurement of a selection box ---
// Frequency-domain stats for the region [t0,t1]x[f0,f1] (all 0-1 normalized;
// f is a fraction of Nyquist). Measured from the STFT magnitude, NOT the
// synchrosqueezed display buffer (which relocates energy for sharpness and
// isn't a faithful per-bin power).
typedef struct {
    bool  valid;
    float peakFreqHz;     // frequency of the strongest bin in the band
    float centroidHz;     // power-weighted mean frequency ("power center")
    float bandwidthHz;    // occupied width: in-band span sitting >3 dB over noise
    float inBandLevelDb;  // mean in-band level, 20*log10(amplitude)
    float snrDb;          // in-band power vs surrounding noise floor (median)
} SpectralStats;

SpectralStats ComputeSpectralStats(const StftResult* stft,
                                   float t0, float t1, float f0, float f1);

// Averaged power spectrum (the "spectrum slice"/PSD curve). Fills the
// caller-provided power[] (length maxBins) with the mean linear power per bin
// (amplitude^2 averaged over the segments in time span [t0,t1], 0-1
// normalized). Returns the number of bins written, 0 on failure. Convert to dB
// at draw time with 10*log10(power).
int ComputePowerSpectrum(const StftResult* stft, float t0, float t1,
                         float* power, int maxBins);

// --- FFT-size handling & cache ---
void ChangeFFTSize(int newFFT);
void SaveToCache(void);
void FreeAllCacheEntries(FFTSizeCache* cache);

#endif // STFT_H
