/*
 * mg_loadrpt_batch.pgc - mg 채널 부하 가중 리포트 배치 (커서 + XA).
 *
 * 채널별 당일 전문건수와 큐 재시도합을 결합한 부하지표(건수 + 재시도*2)를 커서로
 * 훑으며 총 부하와 최대 부하 채널을 집계한다 (트래픽 부하분산 근거용 일배치).
 * Usage: mg_loadrpt_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mg_loadrpt_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    long load;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_chan[16];
    long h_msgcnt, h_retry;
    EXEC SQL END DECLARE SECTION;
    mg_loadrpt_rec_t rec;
    memset(&rec, 0, sizeof(rec));

    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;

    if (tpinit(NULL) < 0) { fprintf(stderr, "tpinit FAIL: %s\n", tpstrerror(tperrno)); return 1; }
    if (tpopen() < 0)     { fprintf(stderr, "tpopen FAIL: %s\n", tpstrerror(tperrno)); return 1; }
    if (tpbegin(60, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL DECLARE lrc CURSOR FOR
        SELECT channel, count(*) FROM mg_msg_log
        WHERE biz_date = :h_bizdate GROUP BY channel ORDER BY channel;
    EXEC SQL OPEN lrc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH lrc INTO :h_chan, :h_msgcnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE lrc; tpabort(0); return 1; }
        rec.channels++;

        h_retry = 0;
        EXEC SQL SELECT coalesce(sum(retry_cnt),0) INTO :h_retry
            FROM mg_queue WHERE biz_date = :h_bizdate AND channel = :h_chan;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE lrc; tpabort(0); return 1; }

        load = h_msgcnt + h_retry * 2;      /* 재시도에 가중 2배 */
        rec.load_sum += load;
        if (load > rec.busiest_load) rec.busiest_load = load;
    }
    EXEC SQL CLOSE lrc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mg_loadrpt_batch COMMIT: bizdate=%s 채널수=%ld 총부하=%ld 최대부하=%ld\n",
           bizdate, rec.channels, rec.load_sum, rec.busiest_load);

    tpclose(); tpterm();
    return 0;
}
