-- concept_links_backfill.sql — 개념↔문항 임베딩 링크 재생성 (Stage B, 멱등·재실행 안전).
-- 정찰 확정: bge-m3 1024d 코사인, per-concept top-k=10, threshold 0.62 → ~2362링크·284/289개념·964문항.
-- 재튜닝 시 DELETE(embedding 소스만) 후 재삽입 = ref 링크(후속) 불변. 개념 doc = 가스기사 태그.
DELETE FROM study_concept_links WHERE link_source = 'embedding';
INSERT INTO study_concept_links (concept_doc_id, question_id, link_source, score)
WITH cd AS (
  SELECT id, embedding FROM documents
  WHERE user_tags::text LIKE '%@library/가스기사/%'
    AND deleted_at IS NULL AND embedding IS NOT NULL
),
ranked AS (
  SELECT cd.id AS concept_doc_id, q.id AS question_id,
         1 - (q.embedding <=> cd.embedding) AS score,
         row_number() OVER (PARTITION BY cd.id ORDER BY q.embedding <=> cd.embedding) AS rn
  FROM cd
  JOIN study_questions q
    ON q.study_topic_id = 4 AND q.embedding IS NOT NULL
   AND q.deleted_at IS NULL AND q.is_active
)
SELECT concept_doc_id, question_id, 'embedding', score
FROM ranked
WHERE rn <= 10 AND score >= 0.62
ON CONFLICT (concept_doc_id, question_id, link_source) DO NOTHING;
