/*
 * mg_peakhour_batch.pgc - mg 시간대별 피크 트래픽 탐지 배치 (커서 + XA).
 *
 * 당일 전문을 생성시각의 시(0~23)로 그룹핑해 시간대별 건수를 커서로 훑으며
 * 최다 건수 시간대를 찾는다 (시간대별 통계에서 피크만 뽑는 일배치판).
 * Usage: mg_peakhour_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mg_peakhour_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_peakhour_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 phc CURSOR FOR
        SELECT extract(hour from created_at)::int AS hh, count(*)
        FROM mg_msg_log WHERE biz_date = :h_bizdate
        GROUP BY hh ORDER BY hh;
    EXEC SQL OPEN phc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH phc INTO :h_hour, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE phc; tpabort(0); return 1; }
        rec.buckets++;
        if (h_cnt > rec.peak_cnt) { rec.peak_cnt = h_cnt; rec.peak_hour = h_hour; }
    }
    EXEC SQL CLOSE phc;

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

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