/*
 * mg_seqrepair_batch.pgc - mg 채널별 순번 결번 보정 통계 배치 (중첩 커서 + XA).
 *
 * 채널을 바깥 커서로, 각 채널의 STAN 을 안쪽 커서로 오름차순 훑으며 채널마다
 * 결번(간격>1) 유무와 최대 결번폭을 잰다 (순번 갭 검출을 채널단위로 세분한 일배치).
 * Usage: mg_seqrepair_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mg_seqrepair_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    long prev, chan_gaps;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_chan[16];
    long h_stan;
    EXEC SQL END DECLARE SECTION;
    mg_seqrepair_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; }

    EXEC SQL DECLARE srchan CURSOR FOR
        SELECT DISTINCT channel FROM mg_msg_log WHERE biz_date = :h_bizdate ORDER BY channel;
    EXEC SQL DECLARE srstan CURSOR FOR
        SELECT DISTINCT stan FROM mg_msg_log
        WHERE biz_date = :h_bizdate AND channel = :h_chan ORDER BY stan;

    EXEC SQL OPEN srchan;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH srchan INTO :h_chan;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE srchan; tpabort(0); return 1; }
        rec.channels++;
        prev = -1; chan_gaps = 0;

        EXEC SQL OPEN srstan;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE srchan; tpabort(0); return 1; }
        for (;;) {
            EXEC SQL FETCH srstan INTO :h_stan;
            if (sqlca.sqlcode == 100) break;
            if (sqlca.sqlcode < 0) { EXEC SQL CLOSE srstan; EXEC SQL CLOSE srchan; tpabort(0); return 1; }
            if (prev >= 0 && h_stan - prev > 1) {
                chan_gaps++;
                if (h_stan - prev - 1 > rec.widest) rec.widest = h_stan - prev - 1;
            }
            prev = h_stan;
        }
        EXEC SQL CLOSE srstan;
        if (chan_gaps > 0) rec.gap_chans++;
    }
    EXEC SQL CLOSE srchan;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mg_seqrepair_batch COMMIT: bizdate=%s 채널수=%ld 결번채널=%ld 최대결번폭=%ld\n",
           bizdate, rec.channels, rec.gap_chans, rec.widest);

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