/*
 * mg_chanload_batch.pgc - mg 채널 부하 점유율 순위 배치 (커서 + XA).
 *
 * 채널별 당일 건수x금액 합성 부하지수를 커서로 내림차순 순회하며
 * 순위표와 최대 부하 채널의 점유율(%) 을 산출한다 (채널 부하 감시).
 * Usage: mg_chanload_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mg_chanload_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    long rank = 0, share;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_chan[16];
    long h_cnt, h_load;
    EXEC SQL END DECLARE SECTION;
    mg_chanload_rec_t rec;
    memset(&rec, 0, sizeof(rec));

    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; }

    /* 부하지수 = 건수*1000 + 금액/10000 (건수 우선, 금액 보정) */
    EXEC SQL DECLARE clb CURSOR FOR
        SELECT channel, count(*),
               count(*) * 1000 + coalesce(sum(amount),0) / 10000
        FROM mg_msg_log WHERE biz_date = :h_bizdate
        GROUP BY channel
        ORDER BY 3 DESC;
    EXEC SQL OPEN clb;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH clb INTO :h_chan, :h_cnt, :h_load;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE clb; tpabort(0); return 1; }
        rank++;
        rec.channels++;
        rec.grand_total += h_load;
        if (rank == 1) { rec.top_load = h_load; strncpy(rec.top_chan, h_chan, sizeof(rec.top_chan)-1); }
        printf("    %ld위 [%s] 건수=%ld 부하지수=%ld\n", rank, h_chan, h_cnt, h_load);
    }
    EXEC SQL CLOSE clb;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    share = (rec.grand_total > 0) ? (rec.top_load * 100L) / rec.grand_total : 0;
    printf(">>> mg_chanload_batch COMMIT: bizdate=%s 채널=%ld개 1위=%s 점유율=%ld%%\n",
           bizdate, rec.channels, rec.top_chan[0] ? rec.top_chan : "-", share);

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