/**
 ******************************************************************************
 * @file    tcp_json_srv.c
 * @author  wangfq
 * @version V1.0
 * @date    2026-06-30
 * @brief   TCP JSON protocol server implementation
 *          DLD960 TCP JSON protocol (port 5960) — auth + 15 commands
 ******************************************************************************
 */

#include "CONFIG.h"
#include "tcp_json_srv.h"
#include "eth_driver.h"
#include "wchnet.h"
#include "net_srv.h"
#include "cmcng.h"
#include "simple_json.h"
#include "storage.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

/*===========================================================================
 * Global State
 *===========================================================================*/
uint8_t  g_json_socket_listen = 0xFF;    // TCP socket ID — handles both listen + client data
TcpJsonAuthState g_json_auth_state = JSON_STATE_WAIT_AUTH;
uint32_t g_json_auth_timer = 0;
uint8_t  g_json_pwd_retry = 0;
uint32_t g_json_lockout_timer = 0;

/*===========================================================================
 * Frame Receive Buffer (line-delimited JSON)
 *===========================================================================*/
static uint8_t  g_json_recv_buf[TCP_JSON_RECV_BUF_LEN];
static uint16_t g_json_recv_len = 0;
static uint8_t  g_json_wchnet_buf[RECE_BUF_LEN];  // WCHNET internal recv buffer

/*===========================================================================
 * Internal helpers
 *===========================================================================*/
static char g_tmp_value[256];        // reusable buffer for simple_parse_json

static void reset_tmp(void) {
    memset(g_tmp_value, 0, sizeof(g_tmp_value));
}

static void json_send_error(uint8_t socket, uint32_t msg_id, const char *cmd,
                             int code, const char *msg) {
    char *out = (char *)malloc(256);
    if (!out) return;
    snprintf(out, 256,
        "{\"msg_id\":%lu,\"cmd\":\"%s\",\"ts\":%lu,\"code\":%d,\"msg\":\"%s\"}\n",
        msg_id, cmd ? cmd : "", (unsigned long)mstick(), code, msg);
    uint32_t slen = strlen(out);
    WCHNET_SocketSend(socket, (uint8_t *)out, &slen);
    free(out);
}

static void json_send_ok(uint8_t socket, uint32_t msg_id, const char *cmd,
                          const char *data_json) {
    char *out = (char *)malloc(TCP_JSON_MAX_FRAME);
    if (!out) return;
    if (data_json && strlen(data_json) > 0) {
        snprintf(out, TCP_JSON_MAX_FRAME,
            "{\"msg_id\":%lu,\"cmd\":\"%s\",\"ts\":%lu,\"code\":0,\"msg\":\"success\",\"data\":%s}\n",
            msg_id, cmd, (unsigned long)mstick(), data_json);
    } else {
        snprintf(out, TCP_JSON_MAX_FRAME,
            "{\"msg_id\":%lu,\"cmd\":\"%s\",\"ts\":%lu,\"code\":0,\"msg\":\"success\"}\n",
            msg_id, cmd, (unsigned long)mstick());
    }
    uint32_t slen = strlen(out);
    WCHNET_SocketSend(socket, (uint8_t *)out, &slen);
    free(out);
}

/* JSON field extractors — parse msg_id, cmd, and data object from raw JSON */
static uint32_t json_get_msg_id(const char *json) {
    reset_tmp();
    simple_parse_json(json, "\"msg_id\"", g_tmp_value);
    if (strlen(g_tmp_value) == 0) return 0;
    return (uint32_t)strtoul(g_tmp_value, NULL, 10);
}


static char *json_get_data_str(const char *json) {
    char *data = (char *)malloc(TCP_JSON_MAX_FRAME);
    if (!data) return NULL;
    memset(data, 0, TCP_JSON_MAX_FRAME);
    simple_parse_json(json, "\"data\"", data);
    if (strlen(data) == 0) {
        free(data);
        return NULL;
    }
    return data;
}

static void json_get_str_field(const char *json, const char *key, char *out, int out_len) {
    reset_tmp();
    simple_parse_json(json, key, g_tmp_value);
    // strip surrounding quotes if present
    char *src = g_tmp_value;
    if (src[0] == '"') src++;
    int len = strlen(src);
    if (len > 0 && src[len - 1] == '"') len--;
    int copy_len = (len < out_len - 1) ? len : out_len - 1;
    memcpy(out, src, copy_len);
    out[copy_len] = '\0';
}

static void json_get_cmd(const char *json, char *out, int out_len) {
    json_get_str_field(json, "\"cmd\"", out, out_len);
}

static uint32_t json_get_uint_field(const char *json, const char *key) {
    reset_tmp();
    simple_parse_json(json, key, g_tmp_value);
    if (strlen(g_tmp_value) == 0) return 0;
    return (uint32_t)strtoul(g_tmp_value, NULL, 10);
}

static uint8_t json_get_bool_field(const char *json, const char *key) {
    reset_tmp();
    simple_parse_json(json, key, g_tmp_value);
    if (strstr(g_tmp_value, "true")) return 1;
    return 0;
}


/*===========================================================================
 * Frame parser: extract line-delimited JSON frames from receive buffer
 *===========================================================================*/
static int json_extract_frame(uint8_t *buf, uint16_t *len, char *frame_out, uint16_t frame_size) {
    uint16_t i;
    for (i = 0; i < *len; i++) {
        if (buf[i] == '\n') {
            uint16_t frame_len = i;
            if (frame_len >= frame_size) frame_len = frame_size - 1;
            memcpy(frame_out, buf, frame_len);
            frame_out[frame_len] = '\0';

            // Remove consumed frame from buffer
            uint16_t remaining = *len - i - 1;
            if (remaining > 0) {
                memmove(buf, buf + i + 1, remaining);
            }
            *len = remaining;
            return 1;
        }
    }
    return 0;  // no complete frame yet
}


/*===========================================================================
 * Command Handlers
 *===========================================================================*/

/* 4.1 pwd_verify */
static void handle_pwd_verify(uint8_t socket, uint32_t msg_id, const char *json) {
    PRINT("JSON: pwd_verify handler entered\n");
    char *data = json_get_data_str(json);
    if (!data) {
        PRINT("JSON: pwd_verify — data is NULL\n");
        json_send_error(socket, msg_id, "pwd_verify", JSON_CODE_PARAM_ERR, "missing data");
        return;
    }
    PRINT("JSON: pwd_verify — data=[%s]\n", data);

    char password[16] = {0};
    json_get_str_field(data, "\"password\"", password, sizeof(password));
    free(data);

    PRINT("JSON: pwd_verify — password=[%s] len=%d\n", password, strlen(password));
    PRINT("JSON: pwd_verify — dev_pwd=[%c%c%c%c%c%c]\n",
          g_dev_password[0], g_dev_password[1], g_dev_password[2],
          g_dev_password[3], g_dev_password[4], g_dev_password[5]);

    if (strlen(password) == 0) {
        json_send_error(socket, msg_id, "pwd_verify", JSON_CODE_PARAM_ERR, "missing password");
        return;
    }

    // Compare password
    if (memcmp(password, g_dev_password, 6) == 0 && strlen(password) == 6) {
        g_json_auth_state = JSON_STATE_AUTHED;
        g_json_pwd_retry = 0;
        g_json_auth_timer = 0;
        json_send_ok(socket, msg_id, "pwd_verify", NULL);
        PRINT("JSON: Auth success\n");
    } else {
        g_json_pwd_retry++;
        if (g_json_pwd_retry >= TCP_JSON_MAX_PWD_RETRY) {
            g_json_auth_state = JSON_STATE_LOCKOUT;
            g_json_lockout_timer = mstick();
            PRINT("JSON: Auth locked out (%d retries)\n", g_json_pwd_retry);
            json_send_error(socket, msg_id, "pwd_verify", JSON_CODE_AUTH_FAIL,
                "password incorrect, locked out for 60s");
        } else {
            json_send_error(socket, msg_id, "pwd_verify", JSON_CODE_AUTH_FAIL, "password incorrect");
        }
    }
}

/* 4.2 dev_serial_set */
static void handle_dev_serial_set(uint8_t socket, uint32_t msg_id, const char *json) {
    char *data = json_get_data_str(json);
    if (!data) {
        json_send_error(socket, msg_id, "dev_serial_set", JSON_CODE_PARAM_ERR, "missing data");
        return;
    }

    char serial[32] = {0};
    json_get_str_field(data, "\"dev_serial\"", serial, sizeof(serial));
    free(data);

    if (strlen(serial) != 12) {
        json_send_error(socket, msg_id, "dev_serial_set", JSON_CODE_PARAM_ERR, "invalid serial length");
        return;
    }

    // Convert hex string to bytes
    uint8_t serial_bytes[6];
    for (int i = 0; i < 6; i++) {
        char hex[3] = {serial[i * 2], serial[i * 2 + 1], '\0'};
        serial_bytes[i] = (uint8_t)strtoul(hex, NULL, 16);
    }

    alter_dev_serila(serial_bytes);
    memcpy(g_dev_number, serial_bytes, 6);
    sprintf(g_dev_number_str, "%02X%02X%02X%02X%02X%02X",
        g_dev_number[0], g_dev_number[1], g_dev_number[2],
        g_dev_number[3], g_dev_number[4], g_dev_number[5]);

    json_send_ok(socket, msg_id, "dev_serial_set", NULL);
    PRINT("JSON: dev_serial_set -> %s\n", g_dev_number_str);
}

/* 4.3 dev_info_query */
static void handle_dev_info_query(uint8_t socket, uint32_t msg_id, const char *json) {
    char data_json[512];
    snprintf(data_json, sizeof(data_json),
        "{\"dev_serial\":\"%s\",\"hard_ver\":\"%s\",\"soft_ver\":\"%s\","
        "\"model\":\"%s\",\"product_code\":\"960001\","
        "\"sub_code\":{\"net\":%s,\"iot\":%s},"
        "\"bus\":{\"bus1\":0,\"bus2\":0,\"bus3\":0,\"bus4\":0}}",
        g_dev_number_str, HARDWARE_VER, FIRMWARE_VER,
        PRODUCT_MODEL,
        g_sub_code_enable.net_enable ? "true" : "false",
        g_sub_code_enable.iot_enable ? "true" : "false");

    json_send_ok(socket, msg_id, "dev_info_query", data_json);
}

/* 4.4 ssc_net_set */
static void handle_ssc_net_set(uint8_t socket, uint32_t msg_id, const char *json) {
    char *data = json_get_data_str(json);
    if (!data) {
        json_send_error(socket, msg_id, "ssc_net_set", JSON_CODE_PARAM_ERR, "missing data");
        return;
    }

    Local_Net_Cfg lcfg = local_net_cfg;  // copy current
    NET_CENTER_INFO ccfg = net_center_info;

    char ip_str[16] = {0};
    json_get_str_field(data, "\"dev_ip\"", ip_str, sizeof(ip_str));
    if (strlen(ip_str) > 0) get_ipstr_to_array(ip_str, lcfg.lip);

    char mask_str[16] = {0};
    json_get_str_field(data, "\"subnet_mask\"", mask_str, sizeof(mask_str));
    if (strlen(mask_str) > 0) get_ipstr_to_array(mask_str, lcfg.sub);

    char gw_str[16] = {0};
    json_get_str_field(data, "\"route_ip\"", gw_str, sizeof(gw_str));
    if (strlen(gw_str) > 0) get_ipstr_to_array(gw_str, lcfg.gw);

    char lssc_ip_str[16] = {0};
    json_get_str_field(data, "\"lssc_ip\"", lssc_ip_str, sizeof(lssc_ip_str));
    if (strlen(lssc_ip_str) > 0) get_ipstr_to_array(lssc_ip_str, ccfg.lssc_ip);

    char dns_str[16] = {0};
    json_get_str_field(data, "\"dns\"", dns_str, sizeof(dns_str));
    if (strlen(dns_str) > 0) get_ipstr_to_array(dns_str, lcfg.dns);

    uint32_t port = json_get_uint_field(data, "\"port\"");
    if (port > 0 && port <= 65535) ccfg.tcp_port = (uint16_t)port;

    free(data);

    // Write to flash and update globals
    write_net_config(&lcfg, &ccfg, &iot_net_info, &g_iot_topic);
    local_net_cfg = lcfg;
    net_center_info = ccfg;

    json_send_ok(socket, msg_id, "ssc_net_set", NULL);
    PRINT("JSON: ssc_net_set done\n");
}

/* 4.5 ssc_net_query */
static void handle_ssc_net_query(uint8_t socket, uint32_t msg_id, const char *json) {
    char data_json[400];
    snprintf(data_json, sizeof(data_json),
        "{\"dev_ip\":\"%d.%d.%d.%d\",\"subnet_mask\":\"%d.%d.%d.%d\","
        "\"route_ip\":\"%d.%d.%d.%d\",\"lssc_ip\":\"%d.%d.%d.%d\","
        "\"dns\":\"%d.%d.%d.%d\",\"port\":%d}",
        local_net_cfg.lip[0], local_net_cfg.lip[1], local_net_cfg.lip[2], local_net_cfg.lip[3],
        local_net_cfg.sub[0], local_net_cfg.sub[1], local_net_cfg.sub[2], local_net_cfg.sub[3],
        local_net_cfg.gw[0], local_net_cfg.gw[1], local_net_cfg.gw[2], local_net_cfg.gw[3],
        net_center_info.lssc_ip[0], net_center_info.lssc_ip[1],
        net_center_info.lssc_ip[2], net_center_info.lssc_ip[3],
        local_net_cfg.dns[0], local_net_cfg.dns[1], local_net_cfg.dns[2], local_net_cfg.dns[3],
        net_center_info.tcp_port);

    json_send_ok(socket, msg_id, "ssc_net_query", data_json);
}

/* 4.6 iot_net_set */
static void handle_iot_net_set(uint8_t socket, uint32_t msg_id, const char *json) {
    char *data = json_get_data_str(json);
    if (!data) {
        json_send_error(socket, msg_id, "iot_net_set", JSON_CODE_PARAM_ERR, "missing data");
        return;
    }

    IOT_NET_INFO icfg = iot_net_info;

    char host[64] = {0};
    json_get_str_field(data, "\"host\"", host, sizeof(host));
    if (strlen(host) > 0) strncpy((char *)icfg.remote_addr, host, 63);

    uint32_t port = json_get_uint_field(data, "\"port\"");
    if (port > 0 && port <= 65535) icfg.mqtt_port = (uint16_t)port;

    char client_id[64] = {0};
    json_get_str_field(data, "\"client_id\"", client_id, sizeof(client_id));
    if (strlen(client_id) > 0) strncpy((char *)icfg.client_id, client_id, 63);

    char username[64] = {0};
    json_get_str_field(data, "\"username\"", username, sizeof(username));
    if (strlen(username) > 0) strncpy((char *)icfg.username, username, 63);

    char password[32] = {0};
    json_get_str_field(data, "\"password\"", password, sizeof(password));
    if (strlen(password) > 0) strncpy((char *)icfg.password, password, 31);

    free(data);

    write_net_config(&local_net_cfg, &net_center_info, &icfg, &g_iot_topic);
    iot_net_info = icfg;

    json_send_ok(socket, msg_id, "iot_net_set", NULL);
    PRINT("JSON: iot_net_set done\n");
}

/* 4.7 iot_net_query */
static void handle_iot_net_query(uint8_t socket, uint32_t msg_id, const char *json) {
    char data_json[400];
    snprintf(data_json, sizeof(data_json),
        "{\"host\":\"%s\",\"port\":%d,\"client_id\":\"%s\","
        "\"username\":\"%s\",\"password\":\"%s\"}",
        iot_net_info.remote_addr, iot_net_info.mqtt_port,
        iot_net_info.client_id, iot_net_info.username, iot_net_info.password);

    json_send_ok(socket, msg_id, "iot_net_query", data_json);
}

/* 4.8 iot_topic_set */
static void handle_iot_topic_set(uint8_t socket, uint32_t msg_id, const char *json) {
    char *data = json_get_data_str(json);
    if (!data) {
        json_send_error(socket, msg_id, "iot_topic_set", JSON_CODE_PARAM_ERR, "missing data");
        return;
    }

    IOT_Topic topic = g_iot_topic;

    topic.clientid_enable = json_get_bool_field(data, "\"client_id_enable\"");

    char topic_pub[64] = {0};
    json_get_str_field(data, "\"topic_pub\"", topic_pub, sizeof(topic_pub));
    if (strlen(topic_pub) > 0) strncpy((char *)topic.topic_pub, topic_pub, 63);

    char topic_sub[64] = {0};
    json_get_str_field(data, "\"topic_sub\"", topic_sub, sizeof(topic_sub));
    if (strlen(topic_sub) > 0) strncpy((char *)topic.topic_sub, topic_sub, 63);

    free(data);

    write_net_config(&local_net_cfg, &net_center_info, &iot_net_info, &topic);
    g_iot_topic = topic;

    json_send_ok(socket, msg_id, "iot_topic_set", NULL);
    PRINT("JSON: iot_topic_set done\n");
}

/* 4.9 iot_topic_query */
static void handle_iot_topic_query(uint8_t socket, uint32_t msg_id, const char *json) {
    char data_json[300];
    snprintf(data_json, sizeof(data_json),
        "{\"client_id_enable\":%s,\"topic_pub\":\"%s\",\"topic_sub\":\"%s\"}",
        g_iot_topic.clientid_enable ? "true" : "false",
        g_iot_topic.topic_pub, g_iot_topic.topic_sub);

    json_send_ok(socket, msg_id, "iot_topic_query", data_json);
}

/* 4.10 pwd_set */
static void handle_pwd_set(uint8_t socket, uint32_t msg_id, const char *json) {
    char *data = json_get_data_str(json);
    if (!data) {
        json_send_error(socket, msg_id, "pwd_set", JSON_CODE_PARAM_ERR, "missing data");
        return;
    }

    char old_pwd[16] = {0}, new_pwd[16] = {0};
    json_get_str_field(data, "\"old_password\"", old_pwd, sizeof(old_pwd));
    json_get_str_field(data, "\"new_password\"", new_pwd, sizeof(new_pwd));
    free(data);

    if (strlen(old_pwd) != 6 || strlen(new_pwd) != 6) {
        json_send_error(socket, msg_id, "pwd_set", JSON_CODE_PARAM_ERR, "password must be 6 digits");
        return;
    }

    if (memcmp(old_pwd, g_dev_password, 6) != 0) {
        json_send_error(socket, msg_id, "pwd_set", JSON_CODE_AUTH_FAIL, "old password incorrect");
        return;
    }

    memcpy(g_dev_password, new_pwd, 6);
    set_ble_safe_pass((uint8_t *)new_pwd);

    json_send_ok(socket, msg_id, "pwd_set", NULL);
    PRINT("JSON: pwd_set done\n");
}

/* 4.11 factory_reset */
static void handle_factory_reset(uint8_t socket, uint32_t msg_id, const char *json) {
    json_send_ok(socket, msg_id, "factory_reset", NULL);
    PRINT("JSON: factory_reset — resetting...\n");

    Delay_Ms(100);
    factory_dev_info();
    Delay_Ms(100);
    NVIC_SystemReset();
}

/* 4.12 device_reset */
static void handle_device_reset(uint8_t socket, uint32_t msg_id, const char *json) {
    // No response — device resets immediately
    char *out = (char *)malloc(128);
    if (out) {
        snprintf(out, 128,
            "{\"msg_id\":%lu,\"cmd\":\"device_reset\",\"ts\":%lu,\"code\":0,\"msg\":\"resetting\"}\n",
            msg_id, (unsigned long)mstick());
        uint32_t slen = strlen(out);
        WCHNET_SocketSend(socket, (uint8_t *)out, &slen);
        free(out);
    }
    Delay_Ms(100);
    NVIC_SystemReset();
}

/* 4.13 loop_param_set */
static void handle_loop_param_set(uint8_t socket, uint32_t msg_id, const char *json) {
    // Forward to Loop MCU via UART2
    // Store params locally for query response
    char *data = json_get_data_str(json);
    if (!data) {
        json_send_error(socket, msg_id, "loop_param_set", JSON_CODE_PARAM_ERR, "missing data");
        return;
    }
    free(data);

    // Build binary packet for Loop MCU (protocol 0x63 = CMD_SET_MCJQ_PARAM)
    // For now, ack the command — full loop MCU integration deferred
    json_send_ok(socket, msg_id, "loop_param_set", NULL);
    PRINT("JSON: loop_param_set (Loop MCU relay pending)\n");
}

/* 4.14 loop_param_query */
static void handle_loop_param_query(uint8_t socket, uint32_t msg_id, const char *json) {
    // Query Loop MCU via UART2 (protocol 0x64 = CMD_GET_MCJQ_PARAM)
    // For now, return stub data — full loop MCU integration deferred
    char data_json[600];
    snprintf(data_json, sizeof(data_json),
        "{\"auto_mode\":false,"
        "\"channels\":["
        "{\"ch\":1,\"sensitivity\":7,\"freq_level\":\"high\",\"loop_delay\":0,"
         "\"output_mode\":\"exist\",\"exist_mode\":0,\"direction_mode\":0,"
         "\"safe_mode\":0,\"function_mode\":0,\"freq_initial\":0,\"freq_current\":0,\"freq_diff\":0},"
        "{\"ch\":2,\"sensitivity\":7,\"freq_level\":\"mid_high\",\"loop_delay\":5,"
         "\"output_mode\":\"exist\",\"exist_mode\":0,\"direction_mode\":0,"
         "\"safe_mode\":0,\"function_mode\":0,\"freq_initial\":0,\"freq_current\":0,\"freq_diff\":0},"
        "{\"ch\":3,\"sensitivity\":5,\"freq_level\":\"mid_low\",\"loop_delay\":0,"
         "\"output_mode\":\"exist\",\"exist_mode\":0,\"direction_mode\":0,"
         "\"safe_mode\":0,\"function_mode\":0,\"freq_initial\":0,\"freq_current\":0,\"freq_diff\":0},"
        "{\"ch\":4,\"sensitivity\":8,\"freq_level\":\"low\",\"loop_delay\":0,"
         "\"output_mode\":\"exist\",\"exist_mode\":0,\"direction_mode\":0,"
         "\"safe_mode\":0,\"function_mode\":0,\"freq_initial\":0,\"freq_current\":0,\"freq_diff\":0}]}");

    json_send_ok(socket, msg_id, "loop_param_query", data_json);
    PRINT("JSON: loop_param_query (stub — Loop MCU relay pending)\n");
}

/* 4.15 report_config */
static void handle_report_config(uint8_t socket, uint32_t msg_id, const char *json) {
    char *data = json_get_data_str(json);
    if (!data) {
        json_send_error(socket, msg_id, "report_config", JSON_CODE_PARAM_ERR, "missing data");
        return;
    }
    // Store report config for future push support
    free(data);
    json_send_ok(socket, msg_id, "report_config", NULL);
    PRINT("JSON: report_config (push not yet implemented)\n");
}


/*===========================================================================
 * Command Dispatch Table
 *===========================================================================*/
typedef struct {
    const char *cmd;
    void (*handler)(uint8_t socket, uint32_t msg_id, const char *json);
    uint8_t need_auth;   // 1 = requires auth, 0 = pre-auth ok
} JsonCmdEntry;

static const JsonCmdEntry g_cmd_table[] = {
    {"pwd_verify",       handle_pwd_verify,       0},
    {"dev_serial_set",   handle_dev_serial_set,   1},
    {"dev_info_query",   handle_dev_info_query,   1},
    {"ssc_net_set",      handle_ssc_net_set,      1},
    {"ssc_net_query",    handle_ssc_net_query,    1},
    {"iot_net_set",      handle_iot_net_set,      1},
    {"iot_net_query",    handle_iot_net_query,    1},
    {"iot_topic_set",    handle_iot_topic_set,    1},
    {"iot_topic_query",  handle_iot_topic_query,  1},
    {"pwd_set",          handle_pwd_set,          1},
    {"factory_reset",    handle_factory_reset,    1},
    {"device_reset",     handle_device_reset,     1},
    {"loop_param_set",   handle_loop_param_set,   1},
    {"loop_param_query", handle_loop_param_query, 1},
    {"report_config",    handle_report_config,    1},
};

#define JSON_CMD_COUNT (sizeof(g_cmd_table) / sizeof(g_cmd_table[0]))


/*===========================================================================
 * Frame Processing
 *===========================================================================*/
static void json_process_frame(uint8_t socket, const char *frame) {
    if (strlen(frame) == 0) return;

    uint32_t msg_id = json_get_msg_id(frame);
    char cmd[32] = {0};
    json_get_cmd(frame, cmd, sizeof(cmd));

    PRINT("JSON dispatch: msg_id=%lu cmd=[%s] len=%d\n", msg_id, cmd, strlen(cmd));

    if (strlen(cmd) == 0) {
        PRINT("JSON: empty cmd, sending error\n");
        json_send_error(socket, msg_id, "", JSON_CODE_PARAM_ERR, "missing cmd field");
        return;
    }

    // Dispatch
    int handled = 0;
    for (int i = 0; i < JSON_CMD_COUNT; i++) {
        if (strcmp(cmd, g_cmd_table[i].cmd) == 0) {
            PRINT("JSON: matched cmd[%d]=%s, need_auth=%d, auth_state=%d\n",
                  i, g_cmd_table[i].cmd, g_cmd_table[i].need_auth, g_json_auth_state);
            // Check auth
            if (g_cmd_table[i].need_auth && g_json_auth_state != JSON_STATE_AUTHED) {
                json_send_error(socket, msg_id, cmd, JSON_CODE_NOT_AUTHED, "not authenticated");
                handled = 1;
                break;
            }
            PRINT("JSON: calling handler for %s\n", cmd);
            g_cmd_table[i].handler(socket, msg_id, frame);
            handled = 1;
            break;
        }
    }

    if (!handled) {
        json_send_error(socket, msg_id, cmd, JSON_CODE_UNSUPPORTED, "unsupported command");
        PRINT("JSON: unsupported cmd: [%s]\n", cmd);
    }
}


/*===========================================================================
 * Public API
 *===========================================================================*/

void tcp_json_srv_init(void) {
    uint8_t ret;
    SOCK_INF sock_inf;

    memset(&sock_inf, 0, sizeof(SOCK_INF));
    sock_inf.SourPort = TCP_JSON_PORT;
    sock_inf.ProtoType = PROTO_TYPE_TCP;
    sock_inf.RecvBufLen = RECE_BUF_LEN;

    ret = WCHNET_SocketCreat(&g_json_socket_listen, &sock_inf);
    if (ret != WCHNET_ERR_SUCCESS) {
        PRINT("JSON: SocketCreat failed: 0x%02X\n", ret);
        return;
    }

    ret = WCHNET_SocketListen(g_json_socket_listen);
    if (ret != WCHNET_ERR_SUCCESS) {
        PRINT("JSON: SocketListen failed: 0x%02X\n", ret);
        return;
    }

    PRINT("JSON: TCP listen on port %d (socket %d)\n", TCP_JSON_PORT, g_json_socket_listen);
}

void tcp_json_handle_sock_int(uint8_t socketid, uint8_t intstat) {
    // Only process events on our TCP listen/data socket
    if (socketid != g_json_socket_listen) return;

    // === CONNECT: client connected — configure recv buffer, init auth state ===
    if (intstat & SINT_STAT_CONNECT) {
        WCHNET_ModifyRecvBuf(socketid, (uint32_t)g_json_wchnet_buf, RECE_BUF_LEN);
        g_json_auth_state = JSON_STATE_WAIT_AUTH;
        g_json_pwd_retry = 0;
        g_json_auth_timer = mstick();
        g_json_recv_len = 0;
        memset(g_json_recv_buf, 0, sizeof(g_json_recv_buf));
        PRINT("JSON: Client connected on socket %d, recv buf configured\n", socketid);
    }

    // === RECV: read and process incoming data ===
    if (intstat & SINT_STAT_RECV) {
        uint32_t recv_len = WCHNET_SocketRecvLen(socketid, NULL);
        if (recv_len > 0) {
            uint16_t space = TCP_JSON_RECV_BUF_LEN - g_json_recv_len;
            if (recv_len > space) recv_len = space;
            uint32_t rd_len = recv_len;
            uint8_t tmp_buf[RECE_BUF_LEN];
            WCHNET_SocketRecv(socketid, tmp_buf, &rd_len);
            memcpy(g_json_recv_buf + g_json_recv_len, tmp_buf, (uint16_t)rd_len);
            g_json_recv_len += (uint16_t)rd_len;

            char frame[TCP_JSON_MAX_FRAME];
            while (json_extract_frame(g_json_recv_buf, &g_json_recv_len, frame, sizeof(frame))) {
                PRINT("JSON recv: %s\n", frame);
                json_process_frame(socketid, frame);
                if (g_json_auth_state == JSON_STATE_WAIT_AUTH) {
                    g_json_auth_timer = mstick();
                }
            }
            if (g_json_recv_len >= TCP_JSON_MAX_FRAME) {
                PRINT("JSON: frame overflow, discarding buffer\n");
                g_json_recv_len = 0;
                memset(g_json_recv_buf, 0, sizeof(g_json_recv_buf));
            }
        }
    }

    // === DISCONNECT: client disconnected, reset state ===
    if (intstat & SINT_STAT_DISCONNECT) {
        PRINT("JSON: Client disconnected (id=%d)\n", socketid);
        g_json_auth_state = JSON_STATE_WAIT_AUTH;
        g_json_pwd_retry = 0;
        g_json_recv_len = 0;
    }

    // === TIMEOUT: connection timed out ===
    if (intstat & SINT_STAT_TIM_OUT) {
        PRINT("JSON: Client timeout (id=%d)\n", socketid);
        g_json_auth_state = JSON_STATE_WAIT_AUTH;
        g_json_pwd_retry = 0;
        g_json_recv_len = 0;
    }
}

void tcp_json_poll(void) {
    // Only poll if we have an active connection (socket configured)
    if (g_json_socket_listen == 0xFF) return;

    // Auth timeout check
    if (g_json_auth_state == JSON_STATE_WAIT_AUTH) {
        if (mstick() - g_json_auth_timer > TCP_JSON_AUTH_TIMEOUT_MS) {
            PRINT("JSON: Auth timeout, closing connection\n");
            WCHNET_SocketClose(g_json_socket_listen, TCP_CLOSE_NORMAL);
            g_json_auth_state = JSON_STATE_WAIT_AUTH;
            g_json_pwd_retry = 0;
            g_json_recv_len = 0;
        }
    }

    // Lockout timeout check
    if (g_json_auth_state == JSON_STATE_LOCKOUT) {
        if (mstick() - g_json_lockout_timer > TCP_JSON_LOCKOUT_TIMEOUT_MS) {
            PRINT("JSON: Lockout expired\n");
            g_json_auth_state = JSON_STATE_WAIT_AUTH;
            g_json_pwd_retry = 0;
        }
    }
}
