/*
 * st_gradestat_batch.pgc - 가맹점 등급별 통계 배치 (XA 배치).
 * 가맹점을 요율(mdr_bps) 등급으로 묶어 등급별 가맹점 수를 커서로 집계하고 최다 등급
 * 요율을 산출해 등급 분포를 출력한다 (집계 전용).
 * 사용법: st_gradestat_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_gradestat_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_gradestat_rec_t rec;
    long topcnt = 0;
    memset(&rec, 0, sizeof(rec));
    EXEC SQL BEGIN DECLARE SECTION;
    long h_bps, h_cnt;
    EXEC SQL END DECLARE SECTION;

    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 gradestat_bc CURSOR FOR
        SELECT mdr_bps, count(*) FROM merchant GROUP BY mdr_bps ORDER BY mdr_bps;
    EXEC SQL OPEN gradestat_bc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH gradestat_bc INTO :h_bps, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE gradestat_bc; tpabort(0); return 1; }
        rec.grades++; rec.merchants += h_cnt;
        if (h_cnt > topcnt) { topcnt = h_cnt; rec.top_bps = h_bps; }
        printf("    GRADE bps=%ld count=%ld\n", h_bps, h_cnt);
    }
    EXEC SQL CLOSE gradestat_bc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> %s COMMIT: bizdate=%s grades=%ld merchants=%ld top_bps=%ld\n",
           ST_GRADESTAT_TAG, bizdate, rec.grades, rec.merchants, rec.top_bps);
    tpclose(); tpterm();
    return 0;
}
