/*
 * au_scorebucket_batch.pgc - au 부정거래 점수대 분포 배치 (CASE + XA).
 *
 * ATMI client: one global transaction; a CASE-summed aggregate splits fraud-log
 * scores into three bands. The C helper maps a score to a label. tpcommit drives
 * XA 2PC. Usage: au_scorebucket_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_scorebucket_batch.h"

/* 점수 → 라벨. */
const char *aub_score_label(long score)
{
    if (score < 50) return "LOW";
    if (score < 80) return "MID";
    return "HIGH";
}

int main(int argc, char **argv)
{
    au_score_ctx_t ctx;
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_low = 0, h_mid = 0, h_high = 0;
    EXEC SQL END DECLARE SECTION;

    memset(&ctx, 0, sizeof(ctx));
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    strncpy(ctx.biz_date, bizdate, sizeof(ctx.biz_date)-1);

    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 SELECT
        coalesce(sum(CASE WHEN score < 50 THEN 1 ELSE 0 END),0),
        coalesce(sum(CASE WHEN score >= 50 AND score < 80 THEN 1 ELSE 0 END),0),
        coalesce(sum(CASE WHEN score >= 80 THEN 1 ELSE 0 END),0)
        INTO :h_low, :h_mid, :h_high
        FROM au_fraud_log WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "au_scorebucket_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    ctx.low = h_low;
    ctx.mid = h_mid;
    ctx.high = h_high;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> au_scorebucket_batch COMMIT: bizdate=%s low=%ld mid=%ld high=%ld peak=%s\n",
           ctx.biz_date, ctx.low, ctx.mid, ctx.high, aub_score_label(ctx.high > 0 ? 80 : 0));

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