/*
 * ac_concentration_batch.pgc - ac 상위매입 집중도 배치 (window + XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction, a windowed subquery ranks purchases and a scalar sums the top-3
 * against the daily total; tpcommit drives XA 2PC.
 * Usage: ac_concentration_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "ac_concentration_batch.h"

/* 집중도(bps) = top_sum / total * 10000. total<=0 이면 0. */
long acb_conc_ratio_bps(long top_sum, long total)
{
    if (total <= 0) return 0;
    return (top_sum * 10000L) / total;
}

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_top = 0, h_total = 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(amount),0) INTO :h_top FROM (
        SELECT amount, row_number() OVER (ORDER BY amount DESC) AS rn
        FROM purchase WHERE biz_date = :h_bizdate) t WHERE t.rn <= 3;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "ac_concentration_batch TOP FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    EXEC SQL SELECT coalesce(sum(amount),0) INTO :h_total FROM purchase WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "ac_concentration_batch TOT FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    ctx.top_sum = h_top;
    ctx.total = h_total;
    ctx.ratio_bps = acb_conc_ratio_bps(ctx.top_sum, ctx.total);

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> ac_concentration_batch COMMIT: bizdate=%s top3=%ld total=%ld ratio_bps=%ld\n",
           ctx.biz_date, ctx.top_sum, ctx.total, ctx.ratio_bps);

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