/*
 * cm_audittop_batch.pgc - cm 감사로그 최다 서비스 배치 (XA).
 *
 * 기준일 공통로그를 서비스별로 그룹핑해 로그가 가장 많은 서비스와 건수를
 * 뽑고, 고유 서비스 수/전체 건수와 함께 요약을 svc=AUDITTOP 로그로 남긴다.
 * 로그 집중도를 감시해 폭주 서비스를 조기에 드러낸다.
 * Usage: cm_audittop_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "cm_audittop_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    cm_audittop_rec_t rec = { 0, 0, 0 };
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_top[64], h_msg[120];
    long h_topcnt, h_distinct, h_total;
    EXEC SQL END DECLARE SECTION;

    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    strcpy(h_top, "NONE");

    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 count(*), count(DISTINCT svc_name) INTO :h_total, :h_distinct
        FROM cm_log WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    rec.total = h_total;
    rec.distinct_svc = h_distinct;

    if (h_total > 0) {
        EXEC SQL SELECT svc_name, count(*) INTO :h_top, :h_topcnt
            FROM cm_log WHERE biz_date = :h_bizdate
            GROUP BY svc_name ORDER BY count(*) DESC, svc_name LIMIT 1;
        if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
        rec.top_cnt = h_topcnt;
    }

    snprintf(h_msg, sizeof(h_msg), "AUDITTOP top=%s cnt=%ld distinct=%ld total=%ld",
             h_top, rec.top_cnt, rec.distinct_svc, rec.total);
    EXEC SQL INSERT INTO cm_log (log_id, svc_name, log_level, msg, biz_date)
        VALUES (nextval('cm_log_seq'), 'AUDITTOP', 'I', :h_msg, :h_bizdate);
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> cm_audittop_batch COMMIT: 최다=%s(%ld) 고유=%ld 전체=%ld\n",
           h_top, rec.top_cnt, rec.distinct_svc, rec.total);

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