/*
 * cm_healthscore_batch.pgc - cm 종합 헬스 스코어 배치 (XA).
 *
 * 당일 로그/환율/채번/파라미터 네 자원의 존재를 각 25점으로 합산해 0~100
 * 스코어를 산출하고 GREEN/YELLOW/RED 등급을 판정한다. 결과를 svc=HSCORE
 * 로그로 남기며, RED 면 종료코드 3 으로 야간 당직에 신호한다.
 * Usage: cm_healthscore_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "cm_healthscore_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    cm_healthscore_rec_t rec = { 0, 0, 0, 0, 0 };
    const char *grade;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_msg[120], h_lvl[4];
    long h_log, h_fx, h_seq, h_param;
    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 SELECT count(*) INTO :h_log FROM cm_log WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    EXEC SQL SELECT count(*) INTO :h_fx FROM cm_fx_rate WHERE base_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    EXEC SQL SELECT count(*) INTO :h_seq FROM cm_seq;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    EXEC SQL SELECT count(*) INTO :h_param FROM cm_param;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }

    rec.log_rows = h_log; rec.fx_rows = h_fx; rec.seq_rows = h_seq; rec.param_rows = h_param;
    if (h_log > 0)   rec.score += 25;
    if (h_fx > 0)    rec.score += 25;
    if (h_seq > 0)   rec.score += 25;
    if (h_param > 0) rec.score += 25;
    grade = (rec.score >= CM_HSCORE_GREEN) ? "GREEN"
          : (rec.score >= CM_HSCORE_YELLOW) ? "YELLOW" : "RED";
    strcpy(h_lvl, (rec.score >= CM_HSCORE_YELLOW) ? "I" : "E");
    snprintf(h_msg, sizeof(h_msg), "HSCORE score=%ld grade=%s", rec.score, grade);
    EXEC SQL INSERT INTO cm_log (log_id, svc_name, log_level, msg, biz_date)
        VALUES (nextval('cm_log_seq'), 'HSCORE', :h_lvl, :h_msg, :h_bizdate);
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> cm_healthscore_batch COMMIT: 스코어=%ld 등급=%s\n", rec.score, grade);

    tpclose(); tpterm();
    return rec.score >= CM_HSCORE_YELLOW ? 0 : 3;
}
