/*
 * mg_hourstat_batch.pgc - mg 시간대별 전문량 집계 배치 (커서 + XA).
 *
 * created_at 의 시(hour) 단위로 당일 전문을 묶어 시간대별 건수를 뽑고
 * 피크아워와 그 비중을 리포트한다 (시간대 세분 통계의 일배치판).
 * Usage: mg_hourstat_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mg_hourstat_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];
    long h_hour, h_cnt;
    EXEC SQL END DECLARE SECTION;
    mg_hourstat_rec_t rec;
    memset(&rec, 0, sizeof(rec));
    rec.peak_hour = -1;

    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 hsc CURSOR FOR
        SELECT extract(hour FROM created_at)::int, count(*)
        FROM mg_msg_log WHERE biz_date = :h_bizdate
        GROUP BY 1 ORDER BY 1;
    EXEC SQL OPEN hsc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH hsc INTO :h_hour, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE hsc; tpabort(0); return 1; }
        rec.hours++;
        rec.total += h_cnt;
        printf("    [%02ld시] %ld건\n", h_hour, h_cnt);
        if (h_cnt > rec.peak_cnt) { rec.peak_cnt = h_cnt; rec.peak_hour = h_hour; }
    }
    EXEC SQL CLOSE hsc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mg_hourstat_batch COMMIT: bizdate=%s 활동시간대=%ld 총=%ld 피크=%ld시(%ld건)\n",
           bizdate, rec.hours, rec.total, rec.peak_hour, rec.peak_cnt);

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