/* @tier medium @module mg @transform msg-gateway-batch */
/*
 * mg_bt_0013.pgc - 전문 처리지연 모니터 배치  [tier=medium]
 *
 * 지정 영업일의 전문 중 수신(recv_ts)~처리(proc_ts) 경과시간이
 * 임계(기본 3초)를 초과한 지연 전문을 커서로 집계하여 지연 건수,
 * 최대 지연, 평균 지연(ms)을 산출하여 리포트한다. (모니터링 전용)
 *
 * 실행:  mg_bt_0013 <YYYYMMDD> [db@host]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "mg_core.h"

EXEC SQL INCLUDE sqlca;

#define MG_LATENCY_THRESH_MS 3000   /* 지연 임계(ms) */

static int run_mg_bt_0013(const char *biz_date)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_biz_date[9];
    char h_key[16];
    long h_lat_ms;
    int  h_thresh;
    EXEC SQL END DECLARE SECTION;

    long scanned = 0, delayed = 0, errcnt = 0;
    long max_lat = 0, sum_lat = 0, avg_lat = 0;

    memset(h_biz_date, 0, sizeof(h_biz_date));
    strncpy(h_biz_date, biz_date, sizeof(h_biz_date) - 1);
    h_thresh = MG_LATENCY_THRESH_MS;

    EXEC SQL DECLARE cur_mg_bt_0013 CURSOR FOR
        SELECT key,
               CAST(EXTRACT(EPOCH FROM (proc_ts - recv_ts)) * 1000 AS bigint)
          FROM mg_ledger
         WHERE biz_date = :h_biz_date
           AND proc_ts IS NOT NULL
           AND EXTRACT(EPOCH FROM (proc_ts - recv_ts)) * 1000 >= :h_thresh
         ORDER BY key;

    EXEC SQL OPEN cur_mg_bt_0013;
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("OPEN cur_mg_bt_0013");
        return TX_EDB;
    }

    for (;;) {
        EXEC SQL FETCH cur_mg_bt_0013 INTO :h_key, :h_lat_ms;

        if (sqlca.sqlcode == TX_SQL_NOTFOUND)
            break;
        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("FETCH cur_mg_bt_0013");
            errcnt++;
            break;
        }

        scanned++;
        delayed++;
        sum_lat += h_lat_ms;
        if (h_lat_ms > max_lat)
            max_lat = h_lat_ms;
        tx_log(TX_LOG_DEBUG, "[mg_bt_0013] 지연 key=%s lat=%ldms", h_key, h_lat_ms);
    }

    EXEC SQL CLOSE cur_mg_bt_0013;

    if (delayed > 0)
        avg_lat = sum_lat / delayed;

    tx_log(TX_LOG_INFO, "[mg_bt_0013] 지연모니터 date=%s 지연=%ld 최대=%ldms",
           biz_date, delayed, max_lat);

    printf("========== 전문 처리지연 모니터 [mg_bt_0013] ==========\n");
    printf("  영업일        : %s\n", biz_date);
    printf("  지연 임계(ms) : %d\n", MG_LATENCY_THRESH_MS);
    printf("  지연 건수     : %ld\n", delayed);
    printf("  최대 지연(ms) : %ld\n", max_lat);
    printf("  평균 지연(ms) : %ld\n", avg_lat);
    printf("  조회 오류     : %ld\n", errcnt);
    printf("=============================================\n");

    return (errcnt == 0) ? TX_OK : TX_FAIL;
}

int main(int argc, char **argv)
{
    const char *biz_date;
    const char *target;
    int rc;

    tx_set_loglevel(TX_LOG_INFO);

    if (argc < 2) {
        fprintf(stderr, "사용법: %s <YYYYMMDD> [db@host]\n", argv[0]);
        return 2;
    }
    biz_date = argv[1];
    target   = (argc >= 3) ? argv[2] : NULL;

    if (!date_is_valid(biz_date)) {
        fprintf(stderr, "오류: 유효하지 않은 영업일 '%s'\n", biz_date);
        return 2;
    }

    tx_log(TX_LOG_INFO, "[mg_bt_0013] 지연 모니터 시작 date=%s", biz_date);

    rc = mg_dbio_connect(target);
    if (rc != TX_OK) {
        tx_log(TX_LOG_ERROR, "[mg_bt_0013] DB 접속 실패 rc=%d", rc);
        return 1;
    }

    rc = run_mg_bt_0013(biz_date);

    mg_dbio_disconnect();

    tx_log(TX_LOG_INFO, "[mg_bt_0013] 배치 종료 rc=%d(%s)", rc, tx_strerror(rc));
    return (rc == TX_OK) ? 0 : 1;
}
