/**
 * MPT (혈액대사판정시험) 항목별 권장치 참고 범위
 * 
 */

export interface MptReferenceRange {
  upperLimit: number | null;
  lowerLimit: number | null;
  unit: string;
  category: '에너지' | '단백질' | '간기능' | '미네랄' | '별도';
}

export const MPT_REFERENCE_RANGES: Record<string, MptReferenceRange> = {
  // 에너지 카테고리
  '글루코스': {
    upperLimit: 72,
    lowerLimit: 46.9,
    unit: 'mg/dL',
    category: '에너지',
  },
  'NEFA': {
    upperLimit: 382,
    lowerLimit: 118,
    unit: 'uEq/L',
    category: '에너지',
  },
  'BHBA': {
    upperLimit: 7.9,
    lowerLimit: 4.3,
    unit: 'mg/dL',
    category: '에너지',
  },
  '콜레스테롤': {
    upperLimit: 169,
    lowerLimit: 117,
    unit: 'mg/dL',
    category: '에너지',
  },

  // 단백질 카테고리
  '알부민': {
    upperLimit: 4.3,
    lowerLimit: 3.3,
    unit: 'g/dL',
    category: '단백질',
  },
  '총글로불린': {
    upperLimit: 36.1,
    lowerLimit: 9.1,
    unit: 'g/L',
    category: '단백질',
  },
  'A/G': {
    upperLimit: 0.4,
    lowerLimit: 0.1,
    unit: '-',
    category: '단백질',
  },
  '요소태질소(BUN)': {
    upperLimit: 18.9,
    lowerLimit: 11.7,
    unit: 'mg/dL',
    category: '단백질',
  },

  // 간기능 카테고리
  'AST': {
    upperLimit: 92,
    lowerLimit: 47,
    unit: 'U/L',
    category: '간기능',
  },
  'GGT': {
    upperLimit: 32,
    lowerLimit: 11,
    unit: 'U/L',
    category: '간기능',
  },
  '지방간 지수': {
    upperLimit: 9.9,
    lowerLimit: -1.2,
    unit: '-',
    category: '간기능',
  },

  // 미네랄 카테고리
  '칼슘': {
    upperLimit: 10.6,
    lowerLimit: 8.1,
    unit: 'mg/dL',
    category: '미네랄',
  },
  '인': {
    upperLimit: 8.9,
    lowerLimit: 6.2,
    unit: 'mg/dL',
    category: '미네랄',
  },
  '칼슘/인': {
    upperLimit: 1.3,
    lowerLimit: 1.2,
    unit: '-',
    category: '미네랄',
  },
  '마그네슘': {
    upperLimit: 3.3,
    lowerLimit: 1.6,
    unit: 'mg/dL',
    category: '미네랄',
  },

  // 별도 카테고리
  '총빌리루빈': {
    upperLimit: null,
    lowerLimit: null,
    unit: 'mg/dL',
    category: '별도',
  },
  '크레아틴': {
    upperLimit: 2.0,
    lowerLimit: 1.0,
    unit: 'mg/dL',
    category: '별도',
  },
};

/**
 * MPT 카테고리 목록 (표시 순서)
 */
export const MPT_CATEGORIES = ['에너지', '단백질', '간기능', '미네랄', '별도'] as const;

/**
 * 측정값이 정상 범위 내에 있는지 확인
 */
export function isWithinRange(
  value: number,
  itemName: string
): 'normal' | 'high' | 'low' | 'unknown' {
  const reference = MPT_REFERENCE_RANGES[itemName];

  if (!reference || reference.upperLimit === null || reference.lowerLimit === null) {
    return 'unknown';
  }

  if (value > reference.upperLimit) return 'high';
  if (value < reference.lowerLimit) return 'low';
  return 'normal';
}

/**
 * 카테고리별로 MPT 항목 그룹화
 */
export function getMptItemsByCategory() {
  const grouped: Record<string, string[]> = {};

  MPT_CATEGORIES.forEach((category) => {
    grouped[category] = [];
  });

  Object.entries(MPT_REFERENCE_RANGES).forEach(([itemName, reference]) => {
    grouped[reference.category].push(itemName);
  });

  return grouped;
}
