-- Phase 2: 일별 종목별 감성 집계 뷰.
-- weighted_score : 소스별 가중치 적용
--   naver_finance 1.0 (가장 직접적인 종목 페이지 뉴스)
--   google_rss    0.7 (관련성 노이즈 있음)
--   dart          0.5 (공시는 short title 만으로는 감성이 약함)

\set ON_ERROR_STOP on

CREATE OR REPLACE VIEW v_sentiment_daily AS
SELECT
  code,
  (published_at AT TIME ZONE 'Asia/Seoul')::date                AS date,
  COUNT(*)                                                       AS n_articles,
  AVG(sentiment_score)::REAL                                     AS mean_score,
  AVG(CASE WHEN sentiment_label = 'positive' THEN 1.0 ELSE 0.0 END)::REAL AS pos_ratio,
  AVG(CASE WHEN sentiment_label = 'negative' THEN 1.0 ELSE 0.0 END)::REAL AS neg_ratio,
  AVG(CASE WHEN sentiment_label = 'neutral'  THEN 1.0 ELSE 0.0 END)::REAL AS neu_ratio,
  AVG(
    sentiment_score * CASE source
      WHEN 'naver_finance' THEN 1.0
      WHEN 'google_rss'    THEN 0.7
      WHEN 'dart'          THEN 0.5
      ELSE 0.6
    END
  )::REAL                                                        AS weighted_score
FROM news
WHERE sentiment_score IS NOT NULL
  AND code IS NOT NULL
GROUP BY code, (published_at AT TIME ZONE 'Asia/Seoul')::date;

COMMENT ON VIEW v_sentiment_daily IS
  'Phase 2: KR-FinBERT 점수를 종목·일(KST) 단위로 집계. Phase 4 LGBM 피처 + UI 차트 보조 데이터로 사용.';
