const { Client } = require('pg');

async function main() {
  const conn = new Client({
    host: 'localhost',
    port: 5432,
    user: 'postgres',
    password: 'turbo123',
    database: 'genome_db'
  });
  await conn.connect();

  // getComparisonAverages가 계산하는 방식 확인
  // 농가 1번의 카테고리별 평균 EBV 계산
  const farmNo = 1;

  // 카테고리 매핑 (백엔드와 동일)
  const TRAIT_CATEGORY_MAP = {
    '12개월령체중': '성장',
    '도체중': '생산', '등심단면적': '생산', '등지방두께': '생산', '근내지방도': '생산',
    '체고': '체형', '십자': '체형', '체장': '체형', '흉심': '체형', '흉폭': '체형',
    '고장': '체형', '요각폭': '체형', '곤폭': '체형', '좌골폭': '체형', '흉위': '체형',
    '안심weight': '무게', '등심weight': '무게', '채끝weight': '무게', '목심weight': '무게',
    '앞다리weight': '무게', '우둔weight': '무게', '설도weight': '무게', '사태weight': '무게',
    '양지weight': '무게', '갈비weight': '무게',
    '안심rate': '비율', '등심rate': '비율', '채끝rate': '비율', '목심rate': '비율',
    '앞다리rate': '비율', '우둔rate': '비율', '설도rate': '비율', '사태rate': '비율',
    '양지rate': '비율', '갈비rate': '비율',
  };

  // 농가 1번의 모든 형질 데이터 조회
  const result = await conn.query(`
    SELECT gtd.trait_name, gtd.trait_ebv
    FROM tb_genome_trait_detail gtd
    JOIN tb_genome_request gr ON gtd.fk_request_no = gr.pk_request_no
    WHERE gr.fk_farm_no = $1
      AND gtd.del_dt IS NULL
      AND gtd.trait_ebv IS NOT NULL
  `, [farmNo]);

  const details = result.rows;
  console.log('농가 1번 전체 형질 데이터 수:', details.length);

  // 카테고리별로 합계 계산
  const categoryMap = {};
  for (const d of details) {
    const category = TRAIT_CATEGORY_MAP[d.trait_name] || '기타';
    if (!categoryMap[category]) {
      categoryMap[category] = { sum: 0, count: 0 };
    }
    categoryMap[category].sum += Number(d.trait_ebv);
    categoryMap[category].count += 1;
  }

  console.log('\n=== getComparisonAverages 방식 (카테고리별 평균) ===');
  const categories = ['성장', '생산', '체형', '무게', '비율'];
  let totalAvgEbv = 0;
  for (const cat of categories) {
    const data = categoryMap[cat];
    const avgEbv = data ? data.sum / data.count : 0;
    console.log(`${cat}: 합계=${data?.sum?.toFixed(2)} / 개수=${data?.count} = 평균 ${avgEbv.toFixed(2)}`);
    totalAvgEbv += avgEbv;
  }

  console.log('\n*** farmAvgZ (카테고리 평균의 합/5):', (totalAvgEbv / categories.length).toFixed(2));

  // getSelectionIndex 방식 비교
  console.log('\n=== getSelectionIndex 방식 (개체별 합계의 평균) ===');
  const farmCowsResult = await conn.query(`
    SELECT c.cow_id, SUM(gtd.trait_ebv) as total_ebv, COUNT(*) as trait_count
    FROM tb_genome_request gr
    JOIN tb_cow c ON gr.fk_cow_no = c.pk_cow_no
    JOIN tb_genome_trait_detail gtd ON gtd.cow_id = c.cow_id AND gtd.del_dt IS NULL
    WHERE gr.fk_farm_no = $1 AND gr.del_dt IS NULL AND c.del_dt IS NULL
      AND gr.chip_sire_name = '일치'
    GROUP BY c.cow_id
    HAVING COUNT(*) = 35
    ORDER BY total_ebv DESC
  `, [farmNo]);
  const farmCows = farmCowsResult.rows;

  let farmSum = 0;
  farmCows.forEach(c => farmSum += Number(c.total_ebv));
  const farmAvgScore = farmCows.length > 0 ? farmSum / farmCows.length : 0;

  console.log(`개체수: ${farmCows.length}`);
  console.log(`*** farmAvgScore (개체별 합계의 평균): ${farmAvgScore.toFixed(2)}`);

  console.log('\n=================================================');
  console.log('farmAvgZ (카테고리 방식):', (totalAvgEbv / categories.length).toFixed(2));
  console.log('farmAvgScore (선발지수 방식):', farmAvgScore.toFixed(2));
  console.log('=================================================');

  await conn.end();
}

main().catch(console.error);
