/*
 * cm_levelstat_batch.pgc - cm 로그 레벨 4분류 CASE 집계 배치 (XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; 정보(I)/경고(W)/오류(E)/기타(NOT IN) 4개 CASE 합계를 한 행으로
 * 집계; then tpcommit drives XA 2PC.
 * Usage: cm_levelstat_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "cm_dbio.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];
    long h_i = 0, h_w = 0, h_e = 0, h_o = 0;
    EXEC SQL END DECLARE SECTION;

    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 SELECT
        coalesce(sum(CASE WHEN log_level = 'I' THEN 1 ELSE 0 END),0),
        coalesce(sum(CASE WHEN log_level = 'W' THEN 1 ELSE 0 END),0),
        coalesce(sum(CASE WHEN log_level = 'E' THEN 1 ELSE 0 END),0),
        coalesce(sum(CASE WHEN log_level NOT IN ('I','W','E') THEN 1 ELSE 0 END),0)
        INTO :h_i, :h_w, :h_e, :h_o FROM cm_log WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "cm_levelstat_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> cm_levelstat_batch COMMIT: bizdate=%s i=%ld w=%ld e=%ld other=%ld\n", bizdate, h_i, h_w, h_e, h_o);

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