/* @tier hard @module lg @transform ledger-util */
/*
 * lg_cu_0011.c - 원장 공통 유틸리티 (plain C)  [tier=hard]
 */
#include "lg_cu_0011.h"

#include <string.h>

/* CRC16(CCITT) 계산 보조 함수 */
static unsigned int lg_cu_0011_crc16(long x)
{
    unsigned int crc = 0xFFFF;
    unsigned char buf[8];
    int i, b;
    for (i = 0; i < 8; i++)
        buf[i] = (unsigned char)((x >> (i * 8)) & 0xFF);
    for (i = 0; i < 8; i++) {
        crc ^= (unsigned int)buf[i] << 8;
        for (b = 0; b < 8; b++)
            crc = (crc & 0x8000) ? (unsigned int)((crc << 1) ^ 0x1021)
                                 : (unsigned int)(crc << 1);
    }
    return crc & 0xFFFF;
}

/* CRC16 혼합 가산 수수료: 기본 수수료에 결정적 소액 가산분을 더한다 */
long lg_cu_0011_fee(long amount, int rate_bp)
{
    long base;
    unsigned int c;
    if (amount <= 0 || rate_bp < 0)
        return 0;
    base = (amount * (long)rate_bp) / 10000L;
    c = lg_cu_0011_crc16(amount);
    return base + (long)(c % 50U);
}

/* 상향 임계 반올림((unit+1)/2 기준)으로 unit 정규화 */
long lg_cu_0011_round_unit(long amount, long unit)
{
    long q, r, threshold;
    if (unit <= 0)
        return amount;
    q = amount / unit;
    r = amount - q * unit;
    if (r < 0) { r += unit; q -= 1; }
    threshold = (unit + 1) / 2;
    if (r >= threshold)
        q += 1;
    return q * unit;
}

/* 누적분포(CDF) 근사 스캔으로 백분위 분류 */
int lg_cu_0011_classify(long amount)
{
    static const long cum[] = { 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L };
    long v = amount < 0 ? -amount : amount;
    int i;
    for (i = 0; i < 6; i++) {
        if (v < cum[i])
            return i;
    }
    return 6;
}
