/*
 * test_m1_integration — M1 exit criterion.
 *
 * Two clients connect to a real voicecat-server over TLS 1.3:
 *   Client A authenticates as guest "GuestBob"
 *   Client B authenticates as password user "alice"
 * Both receive the channel list, A sends a channel message that B receives,
 * then B sends a private message that A receives.
 */
#include <cstdio>
#include <cstring>

#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 EventStore {
    std::mutex              mu;
    std::condition_variable cv;

    bool     auth_ok{false};
    vc_result auth_result{VC_ERR_INTERNAL};
    uint32_t self_user_id{0};
    bool     channel_list_received{false};
    std::vector<std::string> messages;  // copies of received text bodies

    // For diagnostics
    const char* label{nullptr};
    std::string last_error;
    bool disconnected{false};
    vc_connection_state last_state{VC_STATE_DISCONNECTED};

    // 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);
    s->last_state = ev->connection_state;
    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_result = static_cast<vc_result>(ev->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_TEXT_MESSAGE:
            if (ev->text) s->messages.emplace_back(ev->text);
            break;
        case VC_EVENT_ERROR:
            s->last_error = ev->text ? ev->text : "";
            std::fprintf(stderr, "[%s] ERROR rc=%d: %s\n",
                s->label ? s->label : "?", ev->result, s->last_error.c_str());
            break;
        case VC_EVENT_DISCONNECTED:
            s->disconnected = true;
            std::fprintf(stderr, "[%s] DISCONNECTED rc=%d: %s\n",
                s->label ? s->label : "?", ev->result, ev->text ? ev->text : "");
            break;
        case VC_EVENT_CONNECTION_STATE:
            std::fprintf(stderr, "[%s] STATE -> %d\n",
                s->label ? s->label : "?", (int)ev->connection_state);
            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)

// ── main ──────────────────────────────────────────────────────────────────────

int main() {
    // ── Isolated temp dir for this test run ──────────────────────────────────
    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();

    // ── Pre-provision alice's account before the server starts ───────────────
    {
        voicecat::server::Database db(data_dir + "/voicecat.db");
        std::string err;
        if (!db.open(err)) {
            std::printf("FAIL: db.open: %s\n", err.c_str());
            std::filesystem::remove_all(tmp);
            return 1;
        }
        auto acc = db.create_account("alice", "test-pass-alice", false, err);
        if (!acc) {
            std::printf("FAIL: create_account: %s\n", err.c_str());
            std::filesystem::remove_all(tmp);
            return 1;
        }
    }

    // ── Start server on an OS-assigned port ───────────────────────────────────
    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 port
    cfg.server_name  = "VoiceCat-IntTest";
    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("m1_integration: server ready on :%u\n", port);

    // ── Client A: guest "GuestBob" ────────────────────────────────────────────
    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, "GuestBob") == VC_OK);

    // Guest auth is fast; 8s is generous.
    bool authA_ok = wait_for(evA, [](EventStore& s){ return s.auth_ok; }, 8000);
    CHECK(authA_ok);
    if (!authA_ok) std::printf("  (client A auth timed out)\n");

    bool clA_ok = wait_for(evA, [](EventStore& s){ return s.channel_list_received; }, 3000);
    CHECK(clA_ok);

    // ── Client B: password user "alice" ───────────────────────────────────────
    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_user(clientB, "alice", "test-pass-alice") == VC_OK);

    // Argon2id (INTERACTIVE) takes ~0.5-2 s; allow 20 s.
    bool authB_ok = wait_for(evB, [](EventStore& s){ return s.auth_ok; }, 20000);
    CHECK(authB_ok);
    if (!authB_ok) std::printf("  (client B auth timed out — Argon2id may be slow)\n");

    bool clB_ok = wait_for(evB, [](EventStore& s){ return s.channel_list_received; }, 3000);
    CHECK(clB_ok);

    // ── A sends channel text → B receives it ─────────────────────────────────
    const char* chan_msg = "Hello from GuestBob!";
    CHECK(vc_send_text(clientA, VC_TEXT_CHANNEL, 1, chan_msg) == VC_OK);

    bool B_got_chan = wait_for(evB, [&](EventStore& s) {
        for (auto& m : s.messages)
            if (m == chan_msg) return true;
        return false;
    }, 5000);
    CHECK(B_got_chan);

    // ── B sends private text to A ─────────────────────────────────────────────
    uint32_t a_uid = 0;
    { std::lock_guard lk(evA.mu); a_uid = evA.self_user_id; }

    const char* priv_msg = "Private reply from alice!";
    CHECK(vc_send_text(clientB, VC_TEXT_PRIVATE, a_uid, priv_msg) == VC_OK);

    bool A_got_priv = wait_for(evA, [&](EventStore& s) {
        for (auto& m : s.messages)
            if (m == priv_msg) return true;
        return false;
    }, 5000);
    CHECK(A_got_priv);

    // ── 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("m1_integration: all checks passed\n");
        return 0;
    }
    std::printf("m1_integration: %d failure(s)\n", g_failures);
    return 1;
}

#else  // !VOICECAT_HAS_NET

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

#endif  // VOICECAT_HAS_NET
