/*
 * mg_dupscan_batch.pgc - mg 중복 STAN 전문 전수 스캔 배치 (커서 + XA).
 *
 * GROUP BY stan HAVING count(*)>1 커서로 당일 중복 순번 그룹을 전수 조사해
 * 그룹 수/중복 전문 수/최다 중복 STAN 을 리포트한다 (중복전문 검출의 일배치판).
 * Usage: mg_dupscan_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mg_dupscan_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_stan, h_cnt;
    EXEC SQL END DECLARE SECTION;
    mg_dupscan_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 dsc CURSOR FOR
        SELECT stan, count(*) FROM mg_msg_log
        WHERE biz_date = :h_bizdate
        GROUP BY stan HAVING count(*) > 1
        ORDER BY count(*) DESC;
    EXEC SQL OPEN dsc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH dsc INTO :h_stan, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE dsc; tpabort(0); return 1; }
        rec.dup_groups++;
        rec.dup_msgs += h_cnt - 1;             /* 원본 1건 제외한 중복분 */
        if (h_cnt > rec.worst_cnt) { rec.worst_cnt = h_cnt; rec.worst_stan = h_stan; }
    }
    EXEC SQL CLOSE dsc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mg_dupscan_batch COMMIT: bizdate=%s 중복그룹=%ld 중복전문=%ld 최다STAN=%ld(%ld건)\n",
           bizdate, rec.dup_groups, rec.dup_msgs, rec.worst_stan, rec.worst_cnt);

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