#include "r1_voice/conversation.hh"

#include <iostream>
#include <string>

namespace r1_voice {

Conversation::Conversation(
    ConversationConfig config)
    : config_(std::move(config))
    , stt_(config_.stt)
    , llm_(config_.llm)
    , tts_(config_.tts)
    , vision_(config_.vision)
{
}

bool Conversation::init(
    const std::string& network_interface)
{
    return tts_.init(
        network_interface
    );
}

void Conversation::run()
{
    std::cout
        << "\n"
        << "====================================\n"
        << " R1 Voice Assistant\n"
        << "====================================\n"
        << "Speak to R1.\n"
        << "Press Ctrl+C to exit.\n"
        << '\n';

    /*
     * speak() already blocks until playback is done.
     */
    tts_.speak(
        "Ahoj. Jsem připraven."
    );

    while (true) {

        const std::string user =
            stt_.listen();

        if (user.empty())
            continue;

        try {

            std::string response;

            if (vision_.isVisionQuestion(user)) {

                const std::string vision_context =
                    vision_.buildContext();

                std::cout
                    << "[VISION] Visual question detected\n"
                    << "[VISION] "
                    << vision_context
                    << '\n';

                response =
                    llm_.chat(
                        user,
                        vision_context
                    );
            }
            else {

                response =
                    llm_.chat(user);
            }

            if (response.empty())
                continue;

            /*
             * speak() handles the complete playback
             * wait internally.
             */
            tts_.speak(response);
        }
        catch (const std::exception& e) {

            std::cerr
                << "Conversation error: "
                << e.what()
                << '\n';

            tts_.speak(
                "Promiň, při zpracování odpovědi nastala chyba."
            );
        }
    }
}

} // namespace r1_voice
