#include <iostream>
#include <atomic>
#include <csignal>
#include <thread>
#include <chrono>
#include <vector>
#include <fstream>
#include <ctime>
#include <mutex>
#include "utils/Config.h"
#include "audio/AudioCapture.h"
#include "audio/AudioBuffer.h"
#include "api/WhisperClient.h"
#include "api/ClaudeClient.h"

std::atomic<bool> g_running{true};

void signalHandler(int signal) {
    if (signal == SIGINT || signal == SIGTERM) {
        std::cout << "\n\nStopping..." << std::endl;
        g_running = false;
    }
}

int main() {
    std::signal(SIGINT, signalHandler);
    std::signal(SIGTERM, signalHandler);

    std::cout << "========================================" << std::endl;
    std::cout << "SecondVoice - Console Mode" << std::endl;
    std::cout << "========================================" << std::endl;
    std::cout << "Real-time Chinese to French Translation" << std::endl;
    std::cout << std::endl;

    // Load config
    std::cout << "[1/4] Loading configuration..." << std::endl;
    secondvoice::Config& config = secondvoice::Config::getInstance();
    if (!config.load("config.json", ".env")) {
        std::cerr << "ERROR: Failed to load configuration" << std::endl;
        return 1;
    }
    std::cout << "      ✓ Configuration loaded" << std::endl;

    // Initialize audio with VAD-based segmentation
    std::cout << "[2/4] Initializing audio capture..." << std::endl;
    auto& audio_cfg = config.getAudioConfig();
    secondvoice::AudioCapture audio(
        audio_cfg.sample_rate,
        audio_cfg.channels
    );

    if (!audio.initialize()) {
        std::cerr << "ERROR: Failed to initialize audio" << std::endl;
        return 1;
    }
    std::cout << "      ✓ Audio initialized (16kHz, mono)" << std::endl;

    // Initialize API clients
    std::cout << "[3/4] Initializing API clients..." << std::endl;
    secondvoice::WhisperClient whisper(config.getOpenAIKey());
    secondvoice::ClaudeClient claude(config.getAnthropicKey());
    std::cout << "      ✓ Whisper API ready" << std::endl;
    std::cout << "      ✓ Claude API ready" << std::endl;

    // Audio callback
    int chunk_count = 0;
    auto audioCallback = [&](const std::vector<float>& data) {
        chunk_count++;
        std::cout << "\n📼 Chunk #" << chunk_count << " captured (" << data.size() << " samples)" << std::endl;

        // Create audio buffer
        secondvoice::AudioBuffer buffer(audio_cfg.sample_rate, audio_cfg.channels);
        buffer.addSamples(data);

        // Save WAV
        std::time_t now = std::time(nullptr);
        std::string filename = "chunk_" + std::to_string(now) + ".wav";
        if (!buffer.saveToWav(filename)) {
            std::cerr << "  ✗ Failed to save WAV" << std::endl;
            return;
        }
        std::cout << "  ✓ Saved: " << filename << std::endl;

        // Transcribe
        std::cout << "  🔄 Transcribing with Whisper..." << std::flush;
        auto whisper_cfg = config.getWhisperConfig();
        auto transcription = whisper.transcribe(
            data,
            audio_cfg.sample_rate,
            audio_cfg.channels,
            whisper_cfg.language,
            whisper_cfg.prompt
        );

        if (!transcription) {
            std::cout << "\r  ✗ Transcription failed" << std::endl;
            return;
        }

        std::string chinese = transcription->text;
        std::cout << "\r  ✓ Transcribed" << std::endl;
        std::cout << "  中文: " << chinese << std::endl;

        // Translate
        std::cout << "  🔄 Translating with Claude..." << std::flush;
        auto claude_cfg = config.getClaudeConfig();
        auto translation = claude.translate(
            chinese,
            claude_cfg.system_prompt,
            claude_cfg.max_tokens,
            claude_cfg.temperature
        );

        if (!translation) {
            std::cout << "\r  ✗ Translation failed" << std::endl;
            return;
        }

        std::cout << "\r  ✓ Translated" << std::endl;
        std::cout << "  🇫🇷 FR: " << translation->text << std::endl;
    };

    // Start recording
    std::cout << "[4/4] Starting audio recording..." << std::endl;
    if (!audio.start(audioCallback)) {
        std::cerr << "ERROR: Failed to start recording" << std::endl;
        return 1;
    }

    std::cout << std::endl;
    std::cout << "========================================" << std::endl;
    std::cout << "🎤 RECORDING - Speak in Chinese!" << std::endl;
    std::cout << "========================================" << std::endl;
    std::cout << "Press Ctrl+C to stop" << std::endl;
    std::cout << std::endl;

    int seconds = 0;
    while (g_running) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        seconds++;

        if (seconds % 10 == 0 && chunk_count == 0) {
            std::cout << "[" << seconds << "s] Waiting for audio... (Ctrl+C to stop)" << std::endl;
        }
    }

    std::cout << "\n========================================" << std::endl;
    std::cout << "Stopping..." << std::endl;
    audio.stop();
    std::cout << "✓ Done! Processed " << chunk_count << " chunks in " << seconds << " seconds" << std::endl;
    std::cout << "========================================" << std::endl;

    return 0;
}
