/*
 * au_hourly_stat_batch.pgc - au 시간대별 승인 히스토그램 배치 (GROUP 커서 + 배열 적재, XA).
 *
 * 영업일의 승인 접수를 시(0~23) 단위 그룹 커서로 페치해 24칸 히스토그램
 * 배열에 적재한 뒤, C 루프로 피크 시간대를 찾고 오전/오후 분포를 출력한다.
 * Usage: au_hourly_stat_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_hourly_stat_batch.h"

void aub_hourly_find_peak(au_hourly_stat_ctx_t *ctx)
{
    int h;
    ctx->peak_hour = 0;
    ctx->peak_count = 0;
    for (h = 0; h < 24; h++)
        if (ctx->by_hour[h] > ctx->peak_count) {
            ctx->peak_count = ctx->by_hour[h];
            ctx->peak_hour = h;
        }
}

int main(int argc, char **argv)
{
    au_hourly_stat_ctx_t ctx;
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    long am = 0, pm = 0;
    int h;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_hour, h_cnt;
    EXEC SQL END DECLARE SECTION;

    memset(&ctx, 0, sizeof(ctx));
    strncpy(ctx.biz_date, bizdate, sizeof(ctx.biz_date)-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 chsb CURSOR FOR
        SELECT CAST(EXTRACT(HOUR FROM created_at) AS bigint), count(*)
        FROM au_authorization WHERE biz_date = :h_bizdate
        GROUP BY 1 ORDER BY 1;
    EXEC SQL OPEN chsb;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH chsb INTO :h_hour, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE chsb; tpabort(0); return 1; }
        if (h_hour >= 0 && h_hour < 24) ctx.by_hour[h_hour] = h_cnt;
        ctx.total += h_cnt;
    }
    EXEC SQL CLOSE chsb;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }

    aub_hourly_find_peak(&ctx);
    for (h = 0; h < 12; h++) am += ctx.by_hour[h];
    for (h = 12; h < 24; h++) pm += ctx.by_hour[h];
    printf(">>> au_hourly_stat_batch COMMIT: bizdate=%s 총=%ld 피크=%02d시(%ld건) 오전=%ld 오후=%ld\n",
           ctx.biz_date, ctx.total, ctx.peak_hour, ctx.peak_count, am, pm);

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