#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>
#include <algorithm>
#include "acoustic_analyzer/core/feature_extractor.h"
#include "acoustic_analyzer/io/wav_file_source.h"

using namespace acoustic;

int main(int argc, char** argv) {
    if (argc < 2) {
        std::cerr << "Usage: " << argv[0] << " <wav_file> [output_bin]" << std::endl;
        return 1;
    }

    WavFileSource wav(argv[1]);
    if (!wav.open()) {
        std::cerr << "Failed to open WAV" << std::endl;
        return 1;
    }

    std::vector<std::vector<float>> audio;
    wav.read(audio, wav.total_samples());
    if (audio.empty()) {
        std::cerr << "Empty audio" << std::endl;
        return 1;
    }

    FeatureExtractor ext(wav.sample_rate(), 2048, 512, 64);
    Eigen::MatrixXf mel = ext.MelSpectrogram(audio[0]);

    std::cout << "Extracted Mel shape: " << mel.rows() << " x " << mel.cols() << std::endl;

    // Flatten for min/max stats
    std::vector<float> mel_flat(mel.size());
    for (int i = 0; i < mel.rows(); ++i) {
        for (int j = 0; j < mel.cols(); ++j) {
            mel_flat[i * mel.cols() + j] = mel(i, j);
        }
    }
    std::cout << "Min: " << *std::min_element(mel_flat.begin(), mel_flat.end())
              << " Max: " << *std::max_element(mel_flat.begin(), mel_flat.end()) << std::endl;

    if (argc >= 3) {
        std::ofstream out(argv[2], std::ios::binary);
        out.write(reinterpret_cast<const char*>(mel_flat.data()), mel_flat.size() * sizeof(float));
        std::cout << "Saved to " << argv[2] << std::endl;
    }
    return 0;
}
