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();

  // 1. 해당 개체의 형질 데이터 확인
  const cowTraitsResult = await conn.query(
    "SELECT trait_name, trait_ebv FROM tb_genome_trait_detail WHERE cow_id = 'KOR002191643715' AND del_dt IS NULL ORDER BY trait_name"
  );
  const cowTraits = cowTraitsResult.rows;
  console.log('=== 개체 KOR002191643715 형질 데이터 ===');
  console.log('형질수:', cowTraits.length);
  let totalEbv = 0;
  cowTraits.forEach(t => {
    console.log(t.trait_name + ': ' + t.trait_ebv);
    totalEbv += Number(t.trait_ebv || 0);
  });
  console.log('\n*** 내 개체 EBV 합계(선발지수):', totalEbv.toFixed(2));

  // 2. 해당 개체의 농가 확인
  const cowInfoResult = await conn.query(
    "SELECT gr.fk_farm_no, f.farmer_name FROM tb_genome_request gr JOIN tb_cow c ON gr.fk_cow_no = c.pk_cow_no LEFT JOIN tb_farm f ON gr.fk_farm_no = f.pk_farm_no WHERE c.cow_id = 'KOR002191643715' AND gr.del_dt IS NULL LIMIT 1"
  );
  const cowInfo = cowInfoResult.rows;
  console.log('\n=== 농가 정보 ===');
  console.log('농가번호:', cowInfo[0]?.fk_farm_no, '농장주:', cowInfo[0]?.farmer_name);

  const farmNo = cowInfo[0]?.fk_farm_no;

  // 3. 같은 농가의 모든 개체 EBV 합계
  if (farmNo) {
    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;
    console.log('\n=== 같은 농가 개체들 EBV 합계 (35형질 전체) ===');
    console.log('개체수:', farmCows.length);
    let farmSum = 0;
    farmCows.forEach(c => {
      console.log(c.cow_id + ': ' + Number(c.total_ebv).toFixed(2));
      farmSum += Number(c.total_ebv);
    });
    if (farmCows.length > 0) {
      console.log('\n*** 농가 평균:', (farmSum / farmCows.length).toFixed(2));
    }
  }

  // 4. 전체 보은군 평균
  const allCowsResult = await conn.query(
    `SELECT c.cow_id, SUM(gtd.trait_ebv) as total_ebv
     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.del_dt IS NULL AND c.del_dt IS NULL
       AND gr.chip_sire_name = '일치'
     GROUP BY c.cow_id
     HAVING COUNT(*) = 35`
  );
  const allCows = allCowsResult.rows;
  console.log('\n=== 보은군 전체 통계 ===');
  console.log('개체수:', allCows.length);
  let regionSum = 0;
  allCows.forEach(c => regionSum += Number(c.total_ebv));
  if (allCows.length > 0) {
    console.log('*** 보은군 평균:', (regionSum / allCows.length).toFixed(2));
  }

  // 5. 최대/최소 확인
  if (allCows.length > 0) {
    const maxCow = allCows.reduce((max, c) => Number(c.total_ebv) > Number(max.total_ebv) ? c : max, allCows[0]);
    const minCow = allCows.reduce((min, c) => Number(c.total_ebv) < Number(min.total_ebv) ? c : min, allCows[0]);
    console.log('\n최대:', maxCow?.cow_id, Number(maxCow?.total_ebv).toFixed(2));
    console.log('최소:', minCow?.cow_id, Number(minCow?.total_ebv).toFixed(2));
  }

  await conn.end();
}

main().catch(console.error);
