/*
 * test_voice_client_abi — M2 exit criterion, exercised through the real C ABI.
 *
 * Unlike test_m2_voice.cpp (which drives raw BSD sockets to exercise the wire format),
 * this test drives two actual vc_client instances end-to-end: vc_connect, vc_authenticate_guest,
 * vc_stream_start/stop. It proves the client-side voice plane in core/src/core/client.cpp
 * (UDP binding, StreamAnnounce, SessionModel propagation) is wired up for real — not just
 * the raw-socket test harness.
 */
#include <cstdio>

#ifdef VOICECAT_HAS_NET

#include <atomic>
#include <chrono>
#include <condition_variable>
#include <filesystem>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

#include "voicecat.h"
#include "server.h"
#include "db.h"

// ── Event tracking ────────────────────────────────────────────────────────────

struct StreamEvent {
    bool     started;  // true = STARTED, false = STOPPED
    uint32_t user_id;
    uint32_t stream_id;
};

struct EventStore {
    std::mutex              mu;
    std::condition_variable cv;

    bool      auth_ok{false};
    uint32_t  self_user_id{0};
    bool      channel_list_received{false};
    std::vector<StreamEvent> stream_events;

    const char* label{nullptr};
    bool        disconnected{false};

    // Set right after vc_client_create, before vc_connect — lets on_event auto-confirm the
    // M4 TOFU gate (VC_EVENT_SERVER_IDENTITY below) for this headless test.
    vc_client* client{nullptr};
};

static void on_event(void* user, const vc_event* ev) {
    auto* s = static_cast<EventStore*>(user);
    std::lock_guard lk(s->mu);
    switch (ev->type) {
        case VC_EVENT_SERVER_IDENTITY:
            // No human to ask in a headless test — trust on first connect unconditionally.
            vc_confirm_server_identity(s->client, 1);
            break;
        case VC_EVENT_AUTH_RESULT:
            s->auth_ok      = (ev->result == VC_OK);
            s->self_user_id = ev->user_id;
            if (!s->auth_ok) std::fprintf(stderr, "[%s] AUTH FAILED: %s\n",
                s->label ? s->label : "?", ev->text ? ev->text : "(no msg)");
            break;
        case VC_EVENT_CHANNEL_LIST:
            s->channel_list_received = true;
            break;
        case VC_EVENT_STREAM_STARTED:
            s->stream_events.push_back({true, ev->user_id, ev->stream_id});
            break;
        case VC_EVENT_STREAM_STOPPED:
            s->stream_events.push_back({false, ev->user_id, ev->stream_id});
            break;
        case VC_EVENT_ERROR:
            std::fprintf(stderr, "[%s] ERROR rc=%d: %s\n",
                s->label ? s->label : "?", ev->result, ev->text ? ev->text : "");
            break;
        case VC_EVENT_DISCONNECTED:
            s->disconnected = true;
            break;
        default:
            break;
    }
    s->cv.notify_all();
}

template <typename Pred>
static bool wait_for(EventStore& s, Pred pred, int timeout_ms) {
    auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms);
    std::unique_lock lk(s.mu);
    return s.cv.wait_until(lk, deadline, [&] { return pred(s); });
}

// ── Test harness ──────────────────────────────────────────────────────────────

static int g_failures = 0;
#define CHECK(cond)                                                        \
    do {                                                                   \
        if (!(cond)) {                                                     \
            std::printf("FAIL: %s (%s:%d)\n", #cond, __FILE__, __LINE__); \
            ++g_failures;                                                  \
        }                                                                  \
    } while (0)

int main() {
    auto tmp = std::filesystem::temp_directory_path() /
               ("vctest_" + std::to_string(
                   std::chrono::steady_clock::now().time_since_epoch().count()));
    std::filesystem::create_directories(tmp);
    std::string data_dir = tmp.string();

    std::atomic<uint16_t> bound_port{0};
    std::mutex              ready_mu;
    std::condition_variable ready_cv;
    bool                    ready{false};

    voicecat::server::Config cfg;
    cfg.data_dir     = data_dir;
    cfg.bind_port    = 0;       // OS picks the TCP port
    cfg.media_port   = 0;       // OS picks the UDP port
    cfg.server_name  = "VoiceCat-VoiceAbiTest";
    cfg.allow_guests = true;
    cfg.on_ready = [&](uint16_t p) {
        bound_port.store(p);
        { std::lock_guard lk(ready_mu); ready = true; }
        ready_cv.notify_all();
    };

    voicecat::server::Server server(cfg);
    std::thread server_thread([&] { server.run(); });

    {
        std::unique_lock lk(ready_mu);
        bool ok = ready_cv.wait_for(lk, std::chrono::seconds(10), [&] { return ready; });
        if (!ok) {
            std::printf("FAIL: server did not become ready within 10s\n");
            server.stop();
            server_thread.join();
            std::filesystem::remove_all(tmp);
            return 1;
        }
    }

    uint16_t port = bound_port.load();
    std::printf("voice_client_abi: server ready on :%u\n", port);

    // ── Client A: guest "VoiceA" ───────────────────────────────────────────────
    EventStore evA;
    evA.label = "clientA";
    vc_callbacks cbA{on_event, nullptr, &evA};
    vc_config cfgA{"test-clientA", "0.1", VC_LOG_OFF};
    vc_client* clientA = vc_client_create(&cfgA, cbA);
    CHECK(clientA != nullptr);
    evA.client = clientA;

    CHECK(vc_connect(clientA, "127.0.0.1", port) == VC_OK);
    CHECK(vc_authenticate_guest(clientA, "VoiceA") == VC_OK);
    CHECK(wait_for(evA, [](EventStore& s) { return s.auth_ok; }, 8000));
    CHECK(wait_for(evA, [](EventStore& s) { return s.channel_list_received; }, 3000));

    // ── Client B: guest "VoiceB" ───────────────────────────────────────────────
    EventStore evB;
    evB.label = "clientB";
    vc_callbacks cbB{on_event, nullptr, &evB};
    vc_config cfgB{"test-clientB", "0.1", VC_LOG_OFF};
    vc_client* clientB = vc_client_create(&cfgB, cbB);
    CHECK(clientB != nullptr);
    evB.client = clientB;

    CHECK(vc_connect(clientB, "127.0.0.1", port) == VC_OK);
    CHECK(vc_authenticate_guest(clientB, "VoiceB") == VC_OK);
    CHECK(wait_for(evB, [](EventStore& s) { return s.auth_ok; }, 8000));
    CHECK(wait_for(evB, [](EventStore& s) { return s.channel_list_received; }, 3000));

    uint32_t a_uid = 0;
    { std::lock_guard lk(evA.mu); a_uid = evA.self_user_id; }

    // Both guests land in channel 1 (Lobby) automatically; give the async UDP
    // binding handshake (TCP UdpBinding -> ack -> plaintext bootstrap packet) a
    // moment to complete on both clients before announcing a stream.
    std::this_thread::sleep_for(std::chrono::milliseconds(500));

    // ── A announces a MIC stream via the real C ABI ──────────────────────────
    vc_stream_desc desc{};
    desc.kind      = VC_STREAM_MIC;
    desc.device_id = nullptr;
    desc.label     = "mic";

    uint32_t a_stream_id = 0;
    CHECK(vc_stream_start(clientA, &desc, &a_stream_id) == VC_OK);

    // A learns its own stream started.
    bool a_self_started = wait_for(evA, [&](EventStore& s) {
        for (auto& e : s.stream_events)
            if (e.started && e.user_id == a_uid) return true;
        return false;
    }, 5000);
    CHECK(a_self_started);

    // B learns (via UserEvent::UPDATED -> SessionModel -> sync_remote_streams)
    // that A started a stream — this is the cross-client signaling path that
    // was missing while stream_start()/stream_announce_result were stubs.
    bool b_saw_a_started = wait_for(evB, [&](EventStore& s) {
        for (auto& e : s.stream_events)
            if (e.started && e.user_id == a_uid) return true;
        return false;
    }, 5000);
    CHECK(b_saw_a_started);

    // ── A stops the stream ────────────────────────────────────────────────────
    CHECK(vc_stream_stop(clientA, a_stream_id) == VC_OK);

    bool a_self_stopped = wait_for(evA, [&](EventStore& s) {
        for (auto& e : s.stream_events)
            if (!e.started && e.user_id == a_uid) return true;
        return false;
    }, 5000);
    CHECK(a_self_stopped);

    bool b_saw_a_stopped = wait_for(evB, [&](EventStore& s) {
        for (auto& e : s.stream_events)
            if (!e.started && e.user_id == a_uid) return true;
        return false;
    }, 5000);
    CHECK(b_saw_a_stopped);

    // ── Cleanup ───────────────────────────────────────────────────────────────
    vc_disconnect(clientA);
    vc_disconnect(clientB);
    vc_client_destroy(clientA);
    vc_client_destroy(clientB);

    server.stop();
    server_thread.join();

    std::filesystem::remove_all(tmp);

    if (g_failures == 0) {
        std::printf("voice_client_abi: all checks passed\n");
        return 0;
    }
    std::printf("voice_client_abi: %d failure(s)\n", g_failures);
    return 1;
}

#else  // !VOICECAT_HAS_NET

int main() {
    std::printf("voice_client_abi: SKIP (VOICECAT_HAS_NET not defined)\n");
    return 0;
}

#endif  // VOICECAT_HAS_NET
