/*
 * rc_ratestat_batch.pgc - 일자별 대사율 통계 배치 (커서 + XA).
 * 기준일까지의 대사 로그를 영업일 단위로 GROUP BY 집계하는 커서를 돌며
 * 일자별 총건수/MATCHED 건수/대사율(bp)을 표준출력 리포트로 찍는다.
 * 사용법: rc_ratestat_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"
#include "rc_ratestat_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    rc_ratestat_rec_t rec;
    long days = 0;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_day[16];
    long h_tot, h_mat;
    EXEC SQL END DECLARE SECTION;
    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 crb CURSOR FOR
        SELECT to_char(biz_date,'YYYY-MM-DD'), count(*),
               coalesce(sum(CASE WHEN status = 'MATCHED' THEN 1 ELSE 0 END),0)
        FROM rc_match_log
        WHERE biz_date <= :h_bizdate
        GROUP BY biz_date ORDER BY biz_date;
    EXEC SQL OPEN crb;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH crb INTO :h_day, :h_tot, :h_mat;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE crb; tpabort(0); return 1; }
        strncpy(rec.day, h_day, sizeof(rec.day)-1); rec.day[sizeof(rec.day)-1] = 0;
        rec.total = h_tot; rec.matched = h_mat;
        rec.rate_bps = (h_tot > 0) ? (h_mat * 10000) / h_tot : 0;
        printf("    %s total=%ld matched=%ld rate=%ld.%02ld%%\n",
               rec.day, rec.total, rec.matched, rec.rate_bps / 100, rec.rate_bps % 100);
        days++;
    }
    EXEC SQL CLOSE crb;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> %s COMMIT: upto=%s days=%ld\n", RC_RATESTAT_TAG, bizdate, days);

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