// ai-analysis.jsx — AI 가격 예측 + 매수 적기 + 투자 매력도 분석
// 실거래 데이터 + 학술/실무 핵심 요인 + AI 인프라 관점을 통합해
// "어느 정도 오를지 / 언제가 매수 적기인지 / 투자 매력은 어떤지" 산출.

// 단지의 최근 거래들로부터 통계 추출
function tradeStats(trades) {
  if (!trades || !trades.length) return null;
  const prices = trades.map(t => t.price).filter(p => p > 0);
  if (!prices.length) return null;
  const sorted = [...prices].sort((a, b) => a - b);
  const median = sorted[Math.floor(sorted.length / 2)];
  const avg = Math.round(prices.reduce((a, b) => a + b, 0) / prices.length);
  const max = Math.max(...prices), min = Math.min(...prices);
  // 최근/이전 절반 비교로 모멘텀
  const half = Math.floor(trades.length / 2);
  const recent = trades.slice(0, half || 1).map(t => t.price);
  const older = trades.slice(half || 1).map(t => t.price);
  const recentAvg = recent.reduce((a, b) => a + b, 0) / recent.length;
  const olderAvg = older.length ? older.reduce((a, b) => a + b, 0) / older.length : recentAvg;
  const momentum = olderAvg ? ((recentAvg - olderAvg) / olderAvg) * 100 : 0;
  return { median, avg, max, min, count: prices.length, momentum: +momentum.toFixed(2), latest: trades[0].price };
}

// 학술·실무 핵심 요인 가중치 (사용자가 뽑은 요인 + 한국부동산원 리포트 관점)
// SHAP 스타일 기여도. 합 ≈ 100.
const CORE_FACTORS = [
  { id: 'transaction', label: '실거래가 모멘텀', weight: 19, source: '국토부 RTMS', kind: '실무' },
  { id: 'supply', label: '공급(입주물량)', weight: 14, source: '한국부동산원 공급통계', kind: '실무' },
  { id: 'rate', label: '금리·DSR 규제', weight: 13, source: '한국은행 ECOS', kind: '실무' },
  { id: 'transit', label: '교통 호재(GTX·역세권)', weight: 11, source: 'KDI 교통효과 논문', kind: '논문' },
  { id: 'school', label: '학군·학원가', weight: 9, source: '교육통계 + 부동산학회', kind: '논문' },
  { id: 'redev', label: '재건축·재개발 단계', weight: 8, source: 'KB 정비사업 DB', kind: '실무' },
  { id: 'aiinfra', label: 'AI·반도체 인프라 인접', weight: 9, source: '산업단지 + 기업투자', kind: '신규' },
  { id: 'pir', label: 'PIR(소득대비)', weight: 6, source: 'KB PIR 지표', kind: '논문' },
  { id: 'jeonse', label: '전세가율', weight: 6, source: 'KB 주택가격동향', kind: '실무' },
  { id: 'macro', label: '거시(GDP·CPI)', weight: 5, source: '통계청', kind: '논문' },
];

// 종합 AI 분석 — trades(해당 단지 실거래) + region(지역명) 기반
function analyzeUnit({ name, region, trades, area, buildYear }) {
  const stats = tradeStats(trades) || { median: 0, avg: 0, momentum: 0, count: 0, latest: 0 };
  const infra = window.aiInfraFor(region + ' ' + name);

  // ── 요인별 점수(0~100) — 결정적 의사 신호 ──
  const seedNum = [...(name + region)].reduce((h, c) => (h * 31 + c.charCodeAt(0)) % 1000, 7);
  const rnd = (k) => ((seedNum * (k + 3) * 17) % 100);

  const factorScores = {
    transaction: Math.max(20, Math.min(95, 55 + stats.momentum * 4)),
    supply: 40 + rnd(1) * 0.5,
    rate: 58,                          // 동결·완화 기대 반영
    transit: 45 + rnd(2) * 0.5,
    school: 40 + rnd(3) * 0.55,
    redev: 35 + rnd(4) * 0.6,
    aiinfra: infra.score,
    pir: 100 - Math.min(90, (stats.median / 6500) * 2.2),
    jeonse: 48 + rnd(5) * 0.4,
    macro: 60,
  };

  // 가중 종합 점수
  let total = 0, wsum = 0;
  CORE_FACTORS.forEach(f => { total += (factorScores[f.id] || 50) * f.weight; wsum += f.weight; });
  const score = Math.round(total / wsum);

  // ── 12개월 예측 상승률 ──
  // 모멘텀 + AI인프라 + 종합점수 → 연 상승률
  const annualGrowth = +(
    stats.momentum * 0.35 +
    (infra.score - 50) * 0.06 +
    (score - 55) * 0.12
  ).toFixed(1);
  const growthClamped = Math.max(-6, Math.min(18, annualGrowth));

  const base = stats.median || stats.avg || stats.latest || 0;
  const forecast12 = Math.round(base * (1 + growthClamped / 100));

  // ── 매수 적기 ──
  // 점수 높을수록 가까운 시점, 모멘텀 과열(>8%)이면 조정 대기
  let buyMonthsAhead;
  if (stats.momentum > 8) buyMonthsAhead = 5;           // 과열 → 조정 대기
  else if (score >= 82) buyMonthsAhead = 1;
  else if (score >= 72) buyMonthsAhead = 2;
  else if (score >= 62) buyMonthsAhead = 4;
  else buyMonthsAhead = 6;
  const bd = new Date(); bd.setMonth(bd.getMonth() + buyMonthsAhead);
  const bestBuyMonth = `${('' + (bd.getFullYear() % 100)).padStart(2, '0')}.${('' + (bd.getMonth() + 1)).padStart(2, '0')}`;
  const bestBuyDate = `${bd.getFullYear()}-${('' + (bd.getMonth() + 1)).padStart(2, '0')}-01`; // 필터용 ISO(월 1일 기준)
  const bestBuyTs = bd.getTime();
  // 적정 매수가: 점수 높으면 현재가 근처, 낮으면 할인
  const targetPrice = Math.round(base * (score >= 80 ? 0.985 : score >= 70 ? 0.96 : 0.92));

  const confidence = Math.max(58, Math.min(94, score - 4 + (stats.count >= 5 ? 6 : 0)));

  const signal = score >= 84 ? 'BUY' : score >= 76 ? 'ACC' : score >= 64 ? 'WATCH' : score >= 55 ? 'HOLD' : 'AVOID';
  const grade = score >= 85 ? 'S' : score >= 72 ? 'A' : score >= 60 ? 'B' : 'C';

  // ── XAI 핵심 이유 요약 (한 줄) ──
  const reason = buyReasonSummary({ signal, stats, score, infra, annualGrowth: growthClamped, buyMonthsAhead, factorScores });

  return {
    stats, infra, score, grade, signal, confidence,
    annualGrowth: growthClamped, forecast12, bestBuyMonth, bestBuyDate, bestBuyTs, buyMonthsAhead, targetPrice,
    factorScores, factors: CORE_FACTORS, reason,
  };
}

// XAI: AI 의견의 "핵심 이유"를 한 줄로 요약 (지표 조합 기반 결정적 문구)
function buyReasonSummary({ signal, stats, score, infra, annualGrowth, buyMonthsAhead, factorScores }) {
  const parts = [];
  const mom = stats.momentum || 0;
  if (mom > 8) parts.push('실거래가 단기 급등(과열)');
  else if (mom > 2) parts.push('실거래가 상승 모멘텀 확인');
  else if (mom >= -1) parts.push('실거래가 바닥 다지기');
  else parts.push('실거래가 약세·조정 진행');

  if ((stats.count || 0) >= 6) parts.push('거래량 급증');
  else if ((stats.count || 0) >= 3) parts.push('거래량 회복');
  else parts.push('거래 한산');

  if (infra && infra.score >= 70) parts.push('AI·반도체 인프라 인접 수요');
  else if ((factorScores.transit || 0) >= 65) parts.push('교통 호재 인접');
  else if ((factorScores.school || 0) >= 65) parts.push('학군 강세');

  let verdict;
  if (signal === 'BUY') verdict = `즉시 매수 우위 — 적기 ${buyMonthsAhead}개월 내`;
  else if (signal === 'ACC') verdict = `분할 매수 유효 — 적기 ${buyMonthsAhead}개월 내`;
  else if (signal === 'WATCH') verdict = `추세 확인 후 진입 권장`;
  else if (signal === 'HOLD') verdict = `신규 매수보다 보유 관점`;
  else verdict = `하방 위험 — 진입 보류`;

  return { headline: parts.slice(0, 3).join(' · '), verdict };
}

Object.assign(window, { analyzeUnit, tradeStats, CORE_FACTORS, buyReasonSummary });
