#include <libwebsockets.h>
#include <pthread.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include "../src/Common/include/Defs.h"
#include "WebRtcClient.h"

#define MAX_MESSAGE_SIZE 32768
#define MAX_ID_SIZE 128
#define QUEUE_SIZE 128
// Max concurrent calls (parallel connections). Runtime value is set with argv[4].
#define MAX_CALLS_LIMIT 1000
#define DEFAULT_MAX_CALLS 1000
// Safety net (per call) for calls that never receive an explicit HANGUP and whose peer
// connection never reaches FAILED/CLOSED on its own (observed in practice:
// the far end can vanish - e.g. a caller that force-exits via _exit() on
// SDK teardown hangs - without the device's SDK ever signaling failure).
// Comfortably longer than the client's own ConnectTimeout (30s) + HangupGrace
// (2s) so it never fires on a legitimately slow-but-alive call.
#define CALL_WATCHDOG_SECONDS 60

#define DEFAULT_SIGNALING_HOST "lukaxzs.myaddr.io"
#define DEFAULT_SIGNALING_PORT 5000
// Fallbacks, used only when the INVITE does not carry the corresponding field.
#define DEFAULT_STUN_URL "stun:stun.l.google.com:19302"
#define DEFAULT_TURN_URL "turn:lukaxzs.myaddr.io:5002"
#define DEFAULT_TURN_USER "test"
#define DEFAULT_TURN_PASS "test"

// One slot per concurrent call. Slots live in a static array, so a slot pointer is
// stable and is passed to SDK callbacks as customData.
typedef struct {
    volatile uint32_t active;
    // Set from onConnectionState (an SDK callback thread) when the peer
    // connection reaches FAILED/CLOSED on its own. The main loop performs the
    // actual teardown (calling the SDK's teardown from inside its own
    // state-change callback is re-entrant and risks a hang).
    volatile uint32_t peerFailed;
    char callId[MAX_ID_SIZE];
    char userId[MAX_ID_SIZE];
    // ICE transport policy requested by the client in the INVITE ("all" or "relay").
    char icePolicy[16];
    // STUN/TURN config requested by the client in the INVITE. An empty string
    // means "the client explicitly asked for none" (e.g. no TURN server).
    char stunUrl[MAX_ICE_CONFIG_URI_LEN + 1];
    char turnUrl[MAX_ICE_CONFIG_URI_LEN + 1];
    char turnUser[MAX_ICE_CONFIG_CREDENTIAL_LEN + 1];
    char turnPass[MAX_ICE_CONFIG_CREDENTIAL_LEN + 1];
    PRtcPeerConnection peerConnection;
    PRtcRtpTransceiver videoTransceiver;
    PRtcRtpTransceiver audioTransceiver;
    // Wall-clock time the call was accepted; used by the per-call watchdog.
    time_t startTime;
} CallSlot;

static struct {
    struct lws_context* wsContext;
    struct lws* wsi;
    pthread_mutex_t lock;
    char queue[QUEUE_SIZE][MAX_MESSAGE_SIZE];
    uint32_t queueHead;
    uint32_t queueTail;
    char deviceId[MAX_ID_SIZE];
    char receiveBuffer[MAX_MESSAGE_SIZE];
    uint32_t receiveLength;
    CallSlot calls[MAX_CALLS_LIMIT];
    uint32_t maxCalls;
    volatile uint32_t terminate;
} gContext;

static CallSlot* findCall(const char* callId)
{
    uint32_t i;
    for (i = 0; i < gContext.maxCalls; i++) {
        if (gContext.calls[i].active && !strcmp(gContext.calls[i].callId, callId)) return &gContext.calls[i];
    }
    return NULL;
}

static CallSlot* allocCall(void)
{
    uint32_t i;
    for (i = 0; i < gContext.maxCalls; i++) {
        if (!gContext.calls[i].active) return &gContext.calls[i];
    }
    return NULL;
}

static uint32_t activeCallCount(void)
{
    uint32_t i, count = 0;
    for (i = 0; i < gContext.maxCalls; i++) count += gContext.calls[i].active ? 1 : 0;
    return count;
}

static const char* jsonValue(const char* json, const char* field)
{
    char needle[MAX_ID_SIZE];
    const char* value;
    snprintf(needle, sizeof(needle), "\"%s\"", field);
    value = strstr(json, needle);
    if (value == NULL) return NULL;
    value = strchr(value + strlen(needle), ':');
    if (value == NULL) return NULL;
    value++;
    while (*value == ' ' || *value == '\t' || *value == '\r' || *value == '\n') value++;
    return value;
}

static uint32_t jsonString(const char* json, const char* field, char* output, uint32_t size)
{
    const char* value = jsonValue(json, field);
    const char* end;
    if (value == NULL || *value != '"' || size == 0) return 0;
    value++;
    end = strchr(value, '"');
    if (end == NULL || (uint32_t) (end - value) >= size) return 0;
    memcpy(output, value, (size_t) (end - value));
    output[end - value] = '\0';
    return 1;
}

static uint32_t jsonObject(const char* json, const char* field, char* output, uint32_t size)
{
    const char* value = jsonValue(json, field);
    const char* begin;
    int depth = 0;
    uint32_t index = 0;
    uint32_t quoted = 0;
    if (value == NULL || *value != '{' || size == 0) return 0;
    begin = value;
    while (*value != '\0') {
        if (*value == '"' && (value == begin || value[-1] != '\\')) quoted = !quoted;
        if (!quoted && *value == '{') depth++;
        if (!quoted && *value == '}' && --depth == 0) {
            if (index + 1 >= size) return 0;
            output[index++] = *value;
            output[index] = '\0';
            return 1;
        }
        if (index + 1 >= size) return 0;
        output[index++] = *value++;
    }
    return 0;
}

static void wakeWriter(void)
{
    if (gContext.wsContext != NULL) lws_cancel_service(gContext.wsContext);
    if (gContext.wsi != NULL) lws_callback_on_writable(gContext.wsi);
}

static void queueMessage(const char* message)
{
    uint32_t next;
    pthread_mutex_lock(&gContext.lock);
    next = (gContext.queueTail + 1) % QUEUE_SIZE;
    if (next == gContext.queueHead) {
        fprintf(stderr, "[tc01-device] signaling queue full\n");
    } else {
        strncpy(gContext.queue[gContext.queueTail], message, MAX_MESSAGE_SIZE - 1);
        gContext.queue[gContext.queueTail][MAX_MESSAGE_SIZE - 1] = '\0';
        gContext.queueTail = next;
    }
    pthread_mutex_unlock(&gContext.lock);
    wakeWriter();
}

static uint32_t dequeueMessage(char* message, uint32_t size)
{
    uint32_t found = 0;
    pthread_mutex_lock(&gContext.lock);
    if (gContext.queueHead != gContext.queueTail) {
        strncpy(message, gContext.queue[gContext.queueHead], size - 1);
        message[size - 1] = '\0';
        gContext.queueHead = (gContext.queueHead + 1) % QUEUE_SIZE;
        found = 1;
    }
    pthread_mutex_unlock(&gContext.lock);
    return found;
}

static void sendInviteResponse(const char* callId, const char* userId, uint32_t code, const char* message)
{
    char output[MAX_MESSAGE_SIZE];
    snprintf(output, sizeof(output),
             "{\"callId\":\"%s\",\"msgType\":\"RESPONSE\",\"command\":\"INVITE\","
             "\"userId\":\"%s\",\"responseCode\":%u,\"responseMsg\":\"%s\"}",
             callId, userId, code, message);
    queueMessage(output);
}

static void onIceCandidate(uint64_t customData, char* candidate)
{
    char output[MAX_MESSAGE_SIZE];
    CallSlot* call = (CallSlot*) (uintptr_t) customData;
    if (candidate == NULL || call == NULL || !call->active) return;
    snprintf(output, sizeof(output),
             "{\"callId\":\"%s\",\"msgType\":\"REQUEST\",\"command\":\"P2P_HANDSHAKE\","
             "\"userId\":\"%s\",\"content\":{\"method\":\"ICE_CANDIDATE\",\"content\":%s}}",
             call->callId, call->userId, candidate);
    queueMessage(output);
}

static void onConnectionState(uint64_t customData, RTC_PEER_CONNECTION_STATE state)
{
    CallSlot* call = (CallSlot*) (uintptr_t) customData;
    if (call == NULL) return;
    printf("[tc01-device] call %s: peer connection state -> %d (CONNECTED=%d, FAILED=%d, CLOSED=%d)\n",
           call->callId, (int) state,
           (int) RTC_PEER_CONNECTION_STATE_CONNECTED,
           (int) RTC_PEER_CONNECTION_STATE_FAILED,
           (int) RTC_PEER_CONNECTION_STATE_CLOSED);
    fflush(stdout);
    if (state == RTC_PEER_CONNECTION_STATE_FAILED || state == RTC_PEER_CONNECTION_STATE_CLOSED) {
        // Don't touch the SDK (closePeerConnection/freePeerConnection) from
        // here - this runs on the SDK's own callback thread. Just flag it;
        // the main loop tears it down and resets callActive so the device
        // can accept a new INVITE instead of staying stuck BUSY forever.
        call->peerFailed = 1;
        if (gContext.wsContext != NULL) lws_cancel_service(gContext.wsContext);
    }
}

static uint32_t createCallPeerConnection(CallSlot* call)
{
    RtcConfiguration configuration = {0};
    RtcMediaStreamTrack video = {0};
    RtcMediaStreamTrack audio = {0};
    RtcRtpTransceiverInit init = {0};
    uint32_t status;
    uint32_t serverCount = 0;
    // ICE servers come from the INVITE (see handleMessage); empty = not requested.
    if (call->stunUrl[0] != '\0') {
        strncpy(configuration.iceServers[serverCount].urls, call->stunUrl, MAX_ICE_CONFIG_URI_LEN);
        serverCount++;
    }
    if (call->turnUrl[0] != '\0') {
        strncpy(configuration.iceServers[serverCount].urls, call->turnUrl, MAX_ICE_CONFIG_URI_LEN);
        strncpy(configuration.iceServers[serverCount].username, call->turnUser, MAX_ICE_CONFIG_CREDENTIAL_LEN);
        strncpy(configuration.iceServers[serverCount].credential, call->turnPass, MAX_ICE_CONFIG_CREDENTIAL_LEN);
        serverCount++;
    }
    (void) serverCount;
    printf("[tc01-device] call %s: stun=\"%s\" turn=\"%s\" turnUser=\"%s\"\n", call->callId,
           call->stunUrl, call->turnUrl, call->turnUser);
    configuration.iceTransportPolicy = !strcmp(call->icePolicy, "relay") ? ICE_TRANSPORT_POLICY_RELAY : ICE_TRANSPORT_POLICY_ALL;
    printf("[tc01-device] call %s: iceTransportPolicy=%s\n", call->callId, call->icePolicy);
    status = createPeerConnection(&configuration, &call->peerConnection);
    if (status != STATUS_SUCCESS) return status;
    status = peerConnectionOnIceCandidate(call->peerConnection, (uint64_t) (uintptr_t) call, onIceCandidate);
    if (status != STATUS_SUCCESS) return status;
    status = peerConnectionOnConnectionStateChange(call->peerConnection, (uint64_t) (uintptr_t) call, onConnectionState);
    if (status != STATUS_SUCCESS) return status;
    video.kind = MEDIA_STREAM_TRACK_KIND_VIDEO;
    video.codec = RTC_CODEC_H264_PROFILE_42E01F_LEVEL_ASYMMETRY_ALLOWED_PACKETIZATION_MODE;
    strcpy(video.streamId, "tc01-stream");
    strcpy(video.trackId, "tc01-video");
    audio.kind = MEDIA_STREAM_TRACK_KIND_AUDIO;
    audio.codec = RTC_CODEC_OPUS;
    strcpy(audio.streamId, "tc01-stream");
    strcpy(audio.trackId, "tc01-audio");
    init.direction = RTC_RTP_TRANSCEIVER_DIRECTION_SENDONLY;
    if ((status = addSupportedCodec(call->peerConnection, video.codec)) != STATUS_SUCCESS) return status;
    if ((status = addSupportedCodec(call->peerConnection, audio.codec)) != STATUS_SUCCESS) return status;
    if ((status = addTransceiver(call->peerConnection, &video, &init, &call->videoTransceiver)) != STATUS_SUCCESS) return status;
    return addTransceiver(call->peerConnection, &audio, &init, &call->audioTransceiver);
}

static void handleOffer(CallSlot* call, const char* object)
{
    RtcSessionDescriptionInit offer = {0};
    RtcSessionDescriptionInit answer = {0};
    char serialized[MAX_MESSAGE_SIZE];
    char output[MAX_MESSAGE_SIZE];
    uint32_t length = sizeof(serialized);
    char mutableOffer[MAX_MESSAGE_SIZE];
    strncpy(mutableOffer, object, sizeof(mutableOffer) - 1);
    mutableOffer[sizeof(mutableOffer) - 1] = '\0';
    if (deserializeSessionDescriptionInit(mutableOffer, (uint32_t) strlen(mutableOffer), &offer) != STATUS_SUCCESS ||
        setRemoteDescription(call->peerConnection, &offer) != STATUS_SUCCESS ||
        createAnswer(call->peerConnection, &answer) != STATUS_SUCCESS ||
        setLocalDescription(call->peerConnection, &answer) != STATUS_SUCCESS ||
        serializeSessionDescriptionInit(&answer, serialized, &length) != STATUS_SUCCESS) {
        fprintf(stderr, "[tc01-device] call %s: failed to process OFFER\n", call->callId);
        return;
    }
    snprintf(output, sizeof(output),
             "{\"callId\":\"%s\",\"msgType\":\"REQUEST\",\"command\":\"P2P_HANDSHAKE\","
             "\"userId\":\"%s\",\"content\":{\"method\":\"ANSWER\",\"content\":%s}}",
             call->callId, call->userId, serialized);
    queueMessage(output);
}

static void forceEndCall(CallSlot* call, const char* reason)
{
    printf("[tc01-device] call %s ended (%s), active calls before=%u\n", call->callId, reason, activeCallCount());
    fflush(stdout);
    if (call->peerConnection != NULL) {
        closePeerConnection(call->peerConnection);
        freePeerConnection(&call->peerConnection);
    }
    call->videoTransceiver = NULL;
    call->audioTransceiver = NULL;
    call->peerFailed = 0;
    call->active = 0;
}

static void handleMessage(const char* message)
{
    char command[MAX_ID_SIZE];
    char method[MAX_ID_SIZE];
    char incomingCallId[MAX_ID_SIZE] = {0};
    char incomingUserId[MAX_ID_SIZE] = {0};
    char object[MAX_MESSAGE_SIZE];
    char candidate[MAX_MESSAGE_SIZE];
    CallSlot* call;
    if (!jsonString(message, "command", command, sizeof(command))) return;
    jsonString(message, "callId", incomingCallId, sizeof(incomingCallId));
    jsonString(message, "userId", incomingUserId, sizeof(incomingUserId));
    call = findCall(incomingCallId);

    if (!strcmp(command, "INVITE")) {
        if (incomingCallId[0] == '\0' || incomingUserId[0] == '\0') {
            sendInviteResponse(incomingCallId, incomingUserId, 500, "INTERNAL_SERVER_ERROR");
            return;
        }
        if (call != NULL) {
            fprintf(stderr, "[tc01-device] ignoring duplicate INVITE for active callId=%s\n", incomingCallId);
            return;
        }
        call = allocCall();
        if (call == NULL) {
            fprintf(stderr, "[tc01-device] rejecting INVITE callId=%s (BUSY_HERE): activeCalls=%u maxCalls=%u\n",
                    incomingCallId, activeCallCount(), gContext.maxCalls);
            sendInviteResponse(incomingCallId, incomingUserId, 486, "BUSY_HERE");
            return;
        }
        memset(call, 0, sizeof(*call));
        strcpy(call->callId, incomingCallId);
        strcpy(call->userId, incomingUserId);
        // Optional field; anything other than "relay" (or missing) means "all".
        if (!jsonString(message, "iceTransportPolicy", call->icePolicy, sizeof(call->icePolicy))) strcpy(call->icePolicy, "all");
        // STUN/TURN from the INVITE. A field that is absent falls back to the built-in
        // default; a field that is present but empty disables that server.
        if (!jsonString(message, "stunUrl", call->stunUrl, sizeof(call->stunUrl))) strcpy(call->stunUrl, DEFAULT_STUN_URL);
        if (!jsonString(message, "turnUrl", call->turnUrl, sizeof(call->turnUrl))) {
            strcpy(call->turnUrl, DEFAULT_TURN_URL);
            strcpy(call->turnUser, DEFAULT_TURN_USER);
            strcpy(call->turnPass, DEFAULT_TURN_PASS);
        } else {
            jsonString(message, "turnUser", call->turnUser, sizeof(call->turnUser));
            jsonString(message, "turnPass", call->turnPass, sizeof(call->turnPass));
        }
        call->startTime = time(NULL);
        call->active = 1;
        if (createCallPeerConnection(call) != STATUS_SUCCESS) {
            if (call->peerConnection != NULL) {
                closePeerConnection(call->peerConnection);
                freePeerConnection(&call->peerConnection);
            }
            call->active = 0;
            sendInviteResponse(incomingCallId, incomingUserId, 500, "INTERNAL_SERVER_ERROR");
            return;
        }
        sendInviteResponse(incomingCallId, incomingUserId, 200, "OK");
        printf("[tc01-device] accepted INVITE callId=%s userId=%s (active calls=%u/%u)\n",
               incomingCallId, incomingUserId, activeCallCount(), gContext.maxCalls);
        return;
    }

    if (!strcmp(command, "HANGUP")) {
        char output[MAX_MESSAGE_SIZE];
        printf("[tc01-device] received HANGUP for callId=%s (%s)\n", incomingCallId, call != NULL ? "active" : "unknown");
        fflush(stdout);
        if (incomingUserId[0] == '\0' && call != NULL) strcpy(incomingUserId, call->userId);
        if (call != NULL) {
            forceEndCall(call, "HANGUP");
        } else {
            // Unknown/duplicate HANGUP (retry, or crossed with the watchdog): nothing to tear down.
            fprintf(stderr, "[tc01-device] ignoring HANGUP for callId=%s: no such active call\n", incomingCallId);
        }
        snprintf(output, sizeof(output),
                 "{\"callId\":\"%s\",\"msgType\":\"RESPONSE\",\"command\":\"HANGUP\","
                 "\"userId\":\"%s\",\"responseCode\":200,\"responseMsg\":\"OK\"}",
                 incomingCallId, incomingUserId);
        queueMessage(output);
        return;
    }

    if (strcmp(command, "P2P_HANDSHAKE") || call == NULL || !jsonObject(message, "content", object, sizeof(object)) ||
        !jsonString(object, "method", method, sizeof(method))) return;
    if (!jsonObject(object, "content", candidate, sizeof(candidate))) return;
    if (!strcmp(method, "OFFER")) {
        printf("[tc01-device] call %s: received OFFER\n", call->callId);
        handleOffer(call, candidate);
    } else if (!strcmp(method, "ICE_CANDIDATE") && jsonString(candidate, "candidate", object, sizeof(object))) {
        addIceCandidate(call->peerConnection, object);
    }
}

static int callback(struct lws* wsi, enum lws_callback_reasons reason, void* user, void* input, size_t length)
{
    char message[MAX_MESSAGE_SIZE];
    (void) user;
    switch (reason) {
    case LWS_CALLBACK_CLIENT_ESTABLISHED:
        gContext.wsi = wsi;
        snprintf(message, sizeof(message), "{\"type\":\"REGISTER\",\"clientType\":\"device\",\"clientId\":\"%s\"}", gContext.deviceId);
        queueMessage(message);
        break;
    case LWS_CALLBACK_CLIENT_RECEIVE:
        if (gContext.receiveLength + length >= sizeof(gContext.receiveBuffer)) {
            gContext.receiveLength = 0;
            break;
        }
        memcpy(gContext.receiveBuffer + gContext.receiveLength, input, length);
        gContext.receiveLength += (uint32_t) length;
        if (lws_is_final_fragment(wsi)) {
            gContext.receiveBuffer[gContext.receiveLength] = '\0';
            handleMessage(gContext.receiveBuffer);
            gContext.receiveLength = 0;
        }
        break;
    case LWS_CALLBACK_CLIENT_WRITEABLE:
        if (dequeueMessage(message, sizeof(message))) {
            unsigned char buffer[LWS_PRE + MAX_MESSAGE_SIZE];
            size_t lengthToWrite = strlen(message);
            memcpy(buffer + LWS_PRE, message, lengthToWrite);
            lws_write(wsi, buffer + LWS_PRE, lengthToWrite, LWS_WRITE_TEXT);
            wakeWriter();
        }
        break;
    case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
    case LWS_CALLBACK_CLIENT_CLOSED:
        gContext.terminate = 1;
        break;
    case LWS_CALLBACK_EVENT_WAIT_CANCELLED:
        if (gContext.wsi != NULL) lws_callback_on_writable(gContext.wsi);
        break;
    default:
        break;
    }
    return 0;
}

static const struct lws_protocols protocols[] = {
    {"tc01-device", callback, 0, MAX_MESSAGE_SIZE, 0, NULL, 0},
    LWS_PROTOCOL_LIST_TERM
};

static void onSignal(int signalValue)
{
    (void) signalValue;
    gContext.terminate = 1;
    if (gContext.wsContext != NULL) lws_cancel_service(gContext.wsContext);
}

int main(int argc, char** argv)
{
    struct lws_context_creation_info contextInfo = {0};
    struct lws_client_connect_info connectionInfo = {0};
    // usage: tc01_device [deviceId] [host] [port] [maxCalls]
    const char* host = argc > 2 ? argv[2] : "localhost";
    int port = argc > 3 ? atoi(argv[3]) : 8080;
    setvbuf(stdout, NULL, _IOLBF, 0);
    int maxCalls = argc > 4 ? atoi(argv[4]) : DEFAULT_MAX_CALLS;
    uint32_t i;
    strcpy(gContext.deviceId, argc > 1 ? argv[1] : "device-1");
    if (maxCalls < 1) maxCalls = 1;
    if (maxCalls > MAX_CALLS_LIMIT) maxCalls = MAX_CALLS_LIMIT;
    gContext.maxCalls = (uint32_t) maxCalls;
    pthread_mutex_init(&gContext.lock, NULL);
    signal(SIGINT, onSignal);
    if (initWebRtc() != STATUS_SUCCESS) return 1;
    contextInfo.port = CONTEXT_PORT_NO_LISTEN;
    contextInfo.protocols = protocols;
    contextInfo.gid = -1;
    contextInfo.uid = -1;
    gContext.wsContext = lws_create_context(&contextInfo);
    if (gContext.wsContext == NULL) return 2;
    connectionInfo.context = gContext.wsContext;
    connectionInfo.address = host;
    connectionInfo.port = port;
    connectionInfo.path = "/ws";
    connectionInfo.host = host;
    connectionInfo.origin = host;
    connectionInfo.protocol = protocols[0].name;
    if (lws_client_connect_via_info(&connectionInfo) == NULL) return 3;
    printf("[tc01-device] deviceId=%s signaling=ws://%s:%d/ws maxCalls=%u\n", gContext.deviceId, host, port, gContext.maxCalls);
    while (!gContext.terminate) {
        lws_service(gContext.wsContext, 50);
        for (i = 0; i < gContext.maxCalls; i++) {
            CallSlot* call = &gContext.calls[i];
            if (call->active && call->peerFailed) {
                forceEndCall(call, "peer connection FAILED/CLOSED without HANGUP");
            } else if (call->active && (time(NULL) - call->startTime) > CALL_WATCHDOG_SECONDS) {
                forceEndCall(call, "watchdog timeout - no HANGUP or state change received");
            }
        }
    }
    for (i = 0; i < gContext.maxCalls; i++) {
        if (gContext.calls[i].active) forceEndCall(&gContext.calls[i], "shutdown");
    }
    lws_context_destroy(gContext.wsContext);
    deinitWebRtc();
    pthread_mutex_destroy(&gContext.lock);
    return 0;
}