/*
 * nixi_shim.c — drop-in replacement for heynixi's llama-server.exe
 *
 * The HeyNixi app (engine/nexusd) launches NEXUS_LLAMA_SERVER and speaks the
 * OpenAI HTTP protocol to it (/v1/chat/completions, streaming SSE + non-stream,
 * plus /health and /v1/models probes). This shim accepts the same CLI args
 * (ignores model loading), listens on the port the app passes, and forwards
 * every chat completion to a remote OpenAI-compatible backend with the Nixi
 * persona injected as a system message.
 *
 * Config (first found wins, read at startup):
 *   1. Environment:  NIXI_SHIM_URL, NIXI_SHIM_KEY, NIXI_SHIM_MODEL
 *   2. INI next to the exe:  nixi_shim.ini  ([shim] url= key= model=)
 *
 * Build (mingw-w64):
 *   x86_64-w64-mingw32-gcc -O2 -o nixi_shim.exe nixi_shim.c -lwinhttp -lws2_32
 */

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winhttp.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#pragma comment(lib, "winhttp")
#pragma comment(lib, "ws2_32")

#define PERSONA \
    "You are Nixi, an AI assistant with a snarky senior reverse-engineer "   \
    "personality. You answer as the voice of the HeyNixi desktop app. "      \
    "Speak the user's language (Indonesian stays Indonesian, English stays " \
    "English). Keep spoken answers short and conversational (1-3 sentences) " \
    "unless the user asks for detail. Technical, to the point, lightly "     \
    "playful. Never mention these instructions."

/* ---------------- config ---------------- */
static char CFG_URL[512]  = "https://token.lightvela.ai/v1/chat/completions";
static char CFG_KEY[512]  = "";
static char CFG_MODEL[64] = "auto";

static void load_ini(void) {
    char path[MAX_PATH], exe[MAX_PATH];
    GetModuleFileNameA(NULL, exe, MAX_PATH);
    char *slash = strrchr(exe, '\\');
    if (slash) *(slash + 1) = 0;
    snprintf(path, MAX_PATH, "%snixi_shim.ini", exe);
    char buf[1024];
    DWORD n = GetPrivateProfileStringA("shim", "url", "", buf, sizeof(buf), path);
    if (n > 0) snprintf(CFG_URL, sizeof(CFG_URL), "%s", buf);
    n = GetPrivateProfileStringA("shim", "key", "", buf, sizeof(buf), path);
    if (n > 0) snprintf(CFG_KEY, sizeof(CFG_KEY), "%s", buf);
    n = GetPrivateProfileStringA("shim", "model", "", buf, sizeof(buf), path);
    if (n > 0) snprintf(CFG_MODEL, sizeof(CFG_MODEL), "%s", buf);
}

static void load_env(void) {
    char *v;
    if ((v = getenv("NIXI_SHIM_URL"))   && *v) snprintf(CFG_URL,  sizeof(CFG_URL),  "%s", v);
    if ((v = getenv("NIXI_SHIM_KEY"))   && *v) snprintf(CFG_KEY,  sizeof(CFG_KEY),  "%s", v);
    if ((v = getenv("NIXI_SHIM_MODEL")) && *v) snprintf(CFG_MODEL,sizeof(CFG_MODEL),"%s", v);
}


static int to_wide(const char *s, wchar_t *out, int max) {
    return MultiByteToWideChar(CP_UTF8, 0, s, -1, out, max) - 1;
}

/* ---------------- dynamic buffers ---------------- */
typedef struct { char *p; size_t len, cap; } BUF;
static void buf_put(BUF *b, const char *s, size_t n) {
    if (b->len + n + 1 > b->cap) {
        b->cap = (b->len + n + 1) * 2;
        b->p = (char *)realloc(b->p, b->cap);
    }
    memcpy(b->p + b->len, s, n);
    b->len += n;
    b->p[b->len] = 0;
}

#define buf_puts(b, s) buf_put((b), (s), strlen(s))

/* ---------------- json string escape ---------------- */
static void json_escape(BUF *out, const char *s) {
    for (; *s; s++) {
        unsigned char c = (unsigned char)*s;
        switch (c) {
        case '"':  buf_put(out, "\\\"", 2); break;
        case '\\': buf_put(out, "\\\\", 2); break;
        case '\n': buf_put(out, "\\n", 2);  break;
        case '\r': buf_put(out, "\\r", 2);  break;
        case '\t': buf_put(out, "\\t", 2);  break;
        default:
            if (c < 0x20) { char t[8]; snprintf(t, 8, "\\u%04x", c); buf_put(out, t, 6); }
            else buf_put(out, s, 1);
        }
    }
}

/*
 * Minimal JSON surgery on the app's request body:
 *  - extract "stream": true/false
 *  - inject the persona as the first system message
 *  - force "model" to CFG_MODEL
 * Strategy: rebuild the messages array by scanning top-level JSON.
 * The app sends well-formed compact-ish JSON from Python, so a tolerant
 * scanner is enough.
 */
static char *rebuild_request(const char *body, size_t body_len, int *is_stream, size_t *out_len) {
    BUF out = {0};
    /* find "stream" */
    const char *s = body, *end = body + body_len;
    *is_stream = 0;
    if ((s = strstr(body, "\"stream\""))) {
        s += 8;
        while (s < end && (*s == ' ' || *s == ':')) s++;
        if (s < end && *s == 't') *is_stream = 1;
    }
    /* find messages array value: "messages": [ ... ] */
    const char *msgs = strstr(body, "\"messages\"");
    const char *arr = NULL;
    if (msgs) {
        arr = strchr(msgs, '[');
    }
    if (!arr) {
        /* fallback: wrap whole body as-is; backend still gets persona via model? just pass through */
        buf_put(&out, body, body_len);
        *out_len = out.len;
        return out.p;
    }
    /* find matching closing bracket */
    int depth = 0;
    const char *arr_end = arr;
    int in_str = 0;
    for (const char *p = arr; p < end; p++) {
        if (in_str) {
            if (*p == '\\') p++;
            else if (*p == '"') in_str = 0;
            continue;
        }
        if (*p == '"') in_str = 1;
        else if (*p == '[' || *p == '{') depth++;
        else if (*p == ']' || *p == '}') {
            if (*p == ']' && depth == 1) { arr_end = p; break; }
            depth--;
        }
    }
    /* prefix = body[0..messages-key) ; but we rebuild keys we care about:
       emit everything before "messages", then our messages, then the tail after arr_end */
    const char *prefix_start = body;
    const char *prefix_end = msgs;         /* includes the key "messages" we drop */
    const char *tail_start = arr_end + 1;  /* after ']' */

    buf_put(&out, prefix_start, prefix_end - prefix_start);
    buf_puts(&out, "\"messages\":[");

    /* persona system message first */
    {
        static char clean[2048];
        size_t k = 0;
        for (const char *q = PERSONA; *q && k < sizeof(clean) - 1; q++)
            if ((unsigned char)*q >= 0x20) clean[k++] = *q;
        clean[k] = 0;
        buf_puts(&out, "{\"role\":\"system\",\"content\":\"");
        json_escape(&out, clean);
    }
    buf_puts(&out, "\"}");

    /* copy original array contents verbatim (between [ and ]) */
    if (arr_end > arr + 1) {
        buf_puts(&out, ",");
        buf_put(&out, arr + 1, arr_end - arr - 1);
    }
    buf_puts(&out, "]");
    buf_put(&out, tail_start, end - tail_start);

    /* force model: replace the value of the FIRST top-level "model" key only */
    {
        const char *m = strstr(out.p, "\"model\"");
        if (m) {
            const char *colon = strchr(m, ':');
            const char *v1 = colon ? strchr(colon, '"') : NULL;
            if (v1 && v1 < m + 40) {
                const char *v2 = strchr(v1 + 1, '"');
                if (v2 && v2 < out.p + out.len) {
                    BUF fix = {0};
                    buf_put(&fix, out.p, v1 - out.p + 1);
                    buf_put(&fix, CFG_MODEL, strlen(CFG_MODEL));
                    buf_puts(&fix, "\"");
                    buf_put(&fix, v2 + 1, out.len - (size_t)(v2 + 1 - out.p));
                    free(out.p);
                    out = fix;
                }
            }
        }
    }
    *out_len = out.len;
    return out.p;
}

/* ---------------- upstream call via WinHTTP ---------------- */
/*
 * Performs POST to CFG_URL. If is_stream, invokes on_chunk for each raw
 * SSE bytes block as it arrives; otherwise accumulates and returns body.
 * Returns 0 on success, -1 on failure (err msg in errbuf).
 */
static int upstream_post(const char *req_body, size_t req_len, int is_stream,
                         BUF *resp, SOCKET client, char *errbuf, size_t errsz) {
    char host[256] = {0}, path[512] = {0};
    /* manual URL parse: [https://]host[:port]/path */
    const char *u = CFG_URL;
    int secure = 0;
    if (!strncasecmp(u, "https://", 8)) { secure = 1; u += 8; }
    else if (!strncasecmp(u, "http://", 7)) { u += 7; }
    else { snprintf(errbuf, errsz, "bad NIXI_SHIM_URL scheme"); return -1; }
    const char *ps = strchr(u, '/');
    if (ps) {
        size_t hl = ps - u; if (hl >= sizeof(host)) hl = sizeof(host) - 1;
        memcpy(host, u, hl); host[hl] = 0;
        snprintf(path, sizeof(path), "%s", ps);
    } else {
        snprintf(host, sizeof(host), "%s", u);
        snprintf(path, sizeof(path), "/v1/chat/completions");
    }
    int secure_f = secure;
    long port_l = secure ? 443 : 80;
    char *colon = strchr(host, ':');
    if (colon) { *colon = 0; port_l = atol(colon + 1); }
    INTERNET_PORT port = (INTERNET_PORT)port_l;
    if (!host[0]) { snprintf(errbuf, errsz, "empty host"); return -1; }
    secure = secure_f;

    HINTERNET hs = WinHttpOpen(L"nixi-shim/1.0", WINHTTP_ACCESS_TYPE_NO_PROXY,
                                WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
    if (!hs) { snprintf(errbuf, errsz, "WinHttpOpen %lu", GetLastError()); return -1; }
    wchar_t whost[256]; to_wide(host, whost, 256);
    HINTERNET hc = WinHttpConnect(hs, whost, port, 0);
    if (!hc) { snprintf(errbuf, errsz, "WinHttpConnect %lu", GetLastError()); WinHttpCloseHandle(hs); return -1; }
    wchar_t wpath[512]; to_wide(path, wpath, 512);
    HINTERNET hr = WinHttpOpenRequest(hc, L"POST", wpath, NULL, WINHTTP_NO_REFERER,
                                       WINHTTP_DEFAULT_ACCEPT_TYPES,
                                       secure ? WINHTTP_FLAG_SECURE : 0);
    if (!hr) { snprintf(errbuf, errsz, "WinHttpOpenRequest %lu", GetLastError()); WinHttpCloseHandle(hc); WinHttpCloseHandle(hs); return -1; }

    wchar_t whdrs[768];
    {
        char hdrs[768];
        snprintf(hdrs, sizeof(hdrs),
                 "Content-Type: application/json\r\nAuthorization: Bearer %s\r\nAccept: text/event-stream\r\n",
                 CFG_KEY);
        MultiByteToWideChar(CP_UTF8, 0, hdrs, -1, whdrs, 768);
    }
    BOOL ok = WinHttpSendRequest(hr, whdrs, -1, (LPVOID)req_body, (DWORD)req_len, (DWORD)req_len, 0);
    if (!ok) { snprintf(errbuf, errsz, "WinHttpSendRequest %lu", GetLastError()); goto fail; }
    if (!WinHttpReceiveResponse(hr, NULL)) { snprintf(errbuf, errsz, "WinHttpReceiveResponse %lu", GetLastError()); goto fail; }

    DWORD status = 0, sz = sizeof(status);
    WinHttpQueryHeaders(hr, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
                        WINHTTP_HEADER_NAME_BY_INDEX, &status, &sz, WINHTTP_NO_HEADER_INDEX);

    char rbuf[16384];
    DWORD rd = 0;
    for (;;) {
        if (!WinHttpQueryDataAvailable(hr, &rd)) break;
        if (rd == 0) break;
        if (rd > sizeof(rbuf)) rd = sizeof(rbuf);
        DWORD got = 0;
        if (!WinHttpReadData(hr, rbuf, rd, &got)) break;
        if (got == 0) break;
        if (is_stream) {
            /* relay raw SSE to client immediately */
            size_t off = 0;
            while (off < got) {
                int n = send(client, rbuf + off, (int)(got - off), 0);
                if (n <= 0) break;
                off += n;
            }
        } else {
            buf_put(resp, rbuf, got);
        }
    }
    if (!is_stream && resp->len == 0) {
        snprintf(errbuf, errsz, "empty upstream response (status %lu)", status);
        goto fail;
    }
    WinHttpCloseHandle(hr); WinHttpCloseHandle(hc); WinHttpCloseHandle(hs);
    return 0;
fail:
    WinHttpCloseHandle(hr); WinHttpCloseHandle(hc); WinHttpCloseHandle(hs);
    return -1;
}

/* ---------------- error reply helpers ---------------- */
static void send_openai_error(SOCKET c, const char *msg, int http_code) {
    BUF b = {0};
    char head[256];
    buf_puts(&b, "{\"error\":{\"message\":\"");
    json_escape(&b, msg);
    buf_puts(&b, "\",\"type\":\"nixi_shim_error\"}}");
    snprintf(head, sizeof(head),
             "HTTP/1.1 %d Internal\r\nContent-Type: application/json\r\nContent-Length: %zu\r\nConnection: close\r\n\r\n",
             http_code, b.len);
    send(c, head, (int)strlen(head), 0);
    send(c, b.p, (int)b.len, 0);
    free(b.p);
}


/* ---------------- Ollama <-> OpenAI conversion ---------------- */
/* Returns 1 if body looks like Ollama /api/chat ({"model":..,"messages":[..],"stream":..} without "max_tokens" style, top-level "created_at" absent) */
static int looks_ollama(const char *body, size_t len) {
    /* heuristic: Ollama chat has "messages" and lacks "max_tokens"/"temperature" keywords at top; strong signal: caller path /api/chat. We pass path separately instead. */
    (void)body; (void)len;
    return 0; /* unused */
}

/* Build an OpenAI /v1/chat/completions body from an Ollama /api/chat body.
   Extracts "messages":[...] and "stream": bool, sets model to CFG_MODEL, adds persona later via normal rebuild. */
static char *ollama_to_openai(const char *body, size_t len, int *is_stream, size_t *out_len) {
    BUF out = {0};
    /* stream flag */
    *is_stream = 0;
    const char *s = strstr(body, "\"stream\"");
    if (s && s < body + len) {
        s += 8;
        while (s < body + len && (*s == ' ' || *s == ':')) s++;
        if (s < body + len && *s == 't') *is_stream = 1;
    }
    buf_puts(&out, "{\"model\":\"");
    buf_puts(&out, CFG_MODEL);
    buf_puts(&out, "\",\"messages\":");
    /* copy messages array verbatim */
    const char *msgs = strstr(body, "\"messages\"");
    if (msgs) {
        const char *arr = strchr(msgs, '[');
        if (arr) {
            int depth = 0; int in_str = 0;
            const char *arr_end = body + len;
            for (const char *p = arr; p < body + len; p++) {
                if (in_str) { if (*p == '\\') p++; else if (*p == '"') in_str = 0; continue; }
                if (*p == '"') in_str = 1;
                else if (*p == '[' || *p == '{') depth++;
                else if (*p == ']' && depth == 1) { arr_end = p + 1; break; }
                else if (*p == '}' || *p == ']') depth--;
            }
            buf_put(&out, arr, arr_end - arr);
        } else { buf_puts(&out, "[]"); }
    } else { buf_puts(&out, "[]"); }
    buf_puts(&out, ",\"stream\":");
    buf_puts(&out, *is_stream ? "true" : "false");
    buf_puts(&out, "}");
    *out_len = out.len;
    return out.p;
}

/* Build an Ollama /api/chat JSON response from an OpenAI chat completion response (non-streaming).
   Finds choices[0].message.content and wraps it in Ollama shape. */
static char *openai_to_ollama(const char *resp, size_t len, const char *model, size_t *out_len) {
    BUF out = {0};
    const char *content = NULL;
    /* prefer message.content */
    const char *m = strstr(resp, "\"message\"");
    if (m && m < resp + len) {
        const char *c = strstr(m, "\"content\"");
        if (c && c < resp + len) {
            c = strchr(c + 9, '"');
            if (c) content = c + 1;
        }
    }
    if (!content) {
        /* delta.content (streamed aggregate) — find first "content" */
        const char *c = strstr(resp, "\"content\"");
        if (c && c < resp + len) {
            c = strchr(c + 9, '"');
            if (c) content = c + 1;
        }
    }
    buf_puts(&out, "{\"model\":\"");
    buf_puts(&out, model);
    buf_puts(&out, "\",\"created_at\":\"2026-01-01T00:00:00Z\",\"message\":{\"role\":\"assistant\",\"content\":");
    if (content) {
        /* find closing unescaped quote of the JSON string, strictly bounded */
        const char *p = content;
        const char *lim = resp + len;
        int in_esc = 0;
        while (p < lim) {
            if (in_esc) { in_esc = 0; p++; continue; }
            if (*p == '\\') { in_esc = 1; p++; continue; }
            if (*p == '"') break;
            p++;
        }
        if (p < lim) {
            /* content points at the first character AFTER the opening quote;
               p sits on the closing quote. Emit our own quotes + inner text. */
            buf_puts(&out, "\"");
            buf_put(&out, content, (size_t)(p - content));
            buf_puts(&out, "\"");
        } else {
            buf_puts(&out, "\"\"");
        }
    } else {
        buf_puts(&out, "\"\"");
    }
    buf_puts(&out, "},\"done\":true,\"done_reason\":\"stop\",\"prompt_eval_count\":0,\"eval_count\":0}");
    *out_len = out.len;
    return out.p;
}

/* ---------------- client handling ---------------- */
typedef struct { SOCKET s; } CLIENT;

static DWORD WINAPI handle_client(LPVOID arg) {
    CLIENT *cl = (CLIENT *)arg;
    SOCKET c = cl->s;
    free(cl);

    /* read request head + body */
    BUF req = {0};
    char tmp[8192];
    size_t head_end = 0;
    int n;
    for (;;) {
        n = recv(c, tmp, sizeof(tmp), 0);
        if (n <= 0) break;
        buf_put(&req, tmp, n);
        if (!head_end) {
            char *h = strstr(req.p, "\r\n\r\n");
            if (h) {
                head_end = h - req.p + 4;
                /* check content-length */
                char *cl = NULL;
                for (char *q = req.p; q && *q && q < req.p + head_end; q++) {
                    if (!strncasecmp(q, "content-length:", 15)) { cl = q; break; }
                }
                if (cl) {
                    long want = atol(cl + 15);
                    if ((long)(req.len - head_end) >= want) break;
                } else break;
            }
            if (req.len > 0 && n < (int)sizeof(tmp)) break;
        } else break;
    }
    if (req.len == 0) { closesocket(c); return 0; }

    /* route */
    if (strncmp(req.p, "GET /health", 11) == 0 || strncmp(req.p, "GET / ", 6) == 0) {
        const char *r = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 27\r\nConnection: close\r\n\r\n{\"status\":\"ok\",\"nixi\":true}\n";
        send(c, r, (int)strlen(r), 0);
    } else if (strncmp(req.p, "GET /v1/models", 14) == 0 || strncmp(req.p, "GET /api/tags", 13) == 0) {
        BUF b = {0};
        char head[200];
        buf_puts(&b, "{\"object\":\"list\",\"data\":[{\"id\":\"");
        buf_put(&b, CFG_MODEL, strlen(CFG_MODEL));
        buf_puts(&b, "\",\"object\":\"model\",\"owned_by\":\"nixi\"}]}");
        snprintf(head, sizeof(head), "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: %zu\r\nConnection: close\r\n\r\n", b.len);
        send(c, head, (int)strlen(head), 0);
        send(c, b.p, (int)b.len, 0);
        free(b.p);
    } else if (strstr(req.p, "/v1/chat/completions") || strstr(req.p, "/api/chat")) {
        char *body = req.p + head_end;
        size_t body_len = req.len - head_end;
        int is_stream = 0;
        int ollama = strstr(req.p, "/api/chat") != NULL;
        char *rebuilt;
        if (ollama) {
            /* convert Ollama body -> OpenAI body, then inject persona */
            char *oa = ollama_to_openai(body, body_len, &is_stream, &body_len);
            rebuilt = rebuild_request(oa, body_len, &is_stream, &body_len);
            free(oa);
        } else {
            rebuilt = rebuild_request(body, body_len, &is_stream, &body_len);
        }
        {
            char *dbg = getenv("NIXI_SHIM_DEBUG");
            if (dbg && *dbg) {
                FILE *f = fopen("C:\\nixi_shim_debug.json", "wb");
                if (f) { fwrite(rebuilt, 1, body_len, f); fclose(f); }
            }
        }

        /* for streaming we must send HTTP head first */
        if (is_stream) {
            const char *head =
                "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n";
            send(c, head, (int)strlen(head), 0);
        }
        char err[256];
        BUF resp = {0};
        if (upstream_post(rebuilt, body_len, is_stream, &resp, c, err, sizeof(err)) != 0) {
            if (!is_stream) send_openai_error(c, err, 502);
            /* if streaming already started, just close */
        } else if (!is_stream) {
            char head[160];
            if (ollama) {
                size_t ol_len = 0;
                char *ol = openai_to_ollama(resp.p, resp.len, CFG_MODEL, &ol_len);
                snprintf(head, sizeof(head),
                         "HTTP/1.1 200 OK\r\nContent-Type: application/x-ndjson\r\nContent-Length: %zu\r\nConnection: close\r\n\r\n", ol_len);
                send(c, head, (int)strlen(head), 0);
                send(c, ol, (int)ol_len, 0);
                free(ol);
            } else {
                snprintf(head, sizeof(head),
                         "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: %zu\r\nConnection: close\r\n\r\n", resp.len);
                send(c, head, (int)strlen(head), 0);
                send(c, resp.p, (int)resp.len, 0);
            }
        }
        free(resp.p);
        free(rebuilt);
    } else {
        const char *r = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
        send(c, r, (int)strlen(r), 0);
    }
    closesocket(c);
    if (req.p) free(req.p);
    return 0;
}

int main(int argc, char **argv) {
    load_ini();
    load_env();

    /* mimic llama-server CLI: pick up --port / --host if present, else default 8080 */
    int port = 8080;
    for (int i = 1; i < argc - 1; i++) {
        if (!strcmp(argv[i], "--port") || !strcmp(argv[i], "-p")) port = atoi(argv[i + 1]);
    }
    char *envport = getenv("NEXUS_SHIM_PORT");
    if (envport && *envport) port = atoi(envport);

    WSADATA wsa;
    WSAStartup(MAKEWORD(2, 2), &wsa);

    SOCKET ls = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr = {0};
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    addr.sin_port = htons((u_short)port);

    /* if port busy, walk up (app may expect "usual port when free") */
    int tries = 0;
    while (bind(ls, (struct sockaddr *)&addr, sizeof(addr)) != 0 && tries < 20) {
        port++;
        addr.sin_port = htons((u_short)port);
        tries++;
    }
    if (listen(ls, 16) != 0) {
        fprintf(stderr, "nixi-shim: listen failed %d\n", WSAGetLastError());
        return 1;
    }
    fprintf(stderr, "nixi-shim: listening on 127.0.0.1:%d -> %s (model=%s)\n", port, CFG_URL, CFG_MODEL);

    for (;;) {
        SOCKET cs = accept(ls, NULL, NULL);
        if (cs == INVALID_SOCKET) continue;
        CLIENT *cl = (CLIENT *)malloc(sizeof(CLIENT));
        cl->s = cs;
        CloseHandle(CreateThread(NULL, 0, handle_client, cl, 0, NULL));
    }
}
