/*
 * mg_rcfreq_batch.pgc - mg 응답코드별 빈도/오류율 집계 배치 (커서 + XA).
 *
 * 당일 전문을 응답코드(rc)로 그룹핑해 코드 종류 수와 전체 건수를 커서로 누적하고,
 * 정상('00') 외 건수로 오류율(bps)을 산출한다 (응답코드별 통계의 일배치판).
 * Usage: mg_rcfreq_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mg_rcfreq_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_rc[4];
    long h_cnt;
    EXEC SQL END DECLARE SECTION;
    mg_rcfreq_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 rfc CURSOR FOR
        SELECT rc, count(*) FROM mg_msg_log WHERE biz_date = :h_bizdate
        GROUP BY rc ORDER BY rc;
    EXEC SQL OPEN rfc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH rfc INTO :h_rc, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE rfc; tpabort(0); return 1; }
        rec.rc_kinds++;
        rec.total += h_cnt;
        if (strcmp(h_rc, "00") != 0) rec.err += h_cnt;
    }
    EXEC SQL CLOSE rfc;
    rec.err_bps = (rec.total > 0) ? (rec.err * 10000L) / rec.total : 0;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mg_rcfreq_batch COMMIT: bizdate=%s 코드종류=%ld 총건=%ld 오류건=%ld 오류율=%ldbps\n",
           bizdate, rec.rc_kinds, rec.total, rec.err, rec.err_bps);

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