#!/bin/bash
# Qdrant 컬렉션 설정: tk_company 생성 + chat_memory 인덱스 추가
# 실행: bash init/setup-qdrant.sh

QDRANT_URL="${QDRANT_URL:-http://localhost:6333}"

echo "=== Qdrant 컬렉션 설정 ==="

# 1. tk_company 컬렉션 생성 (bge-m3: 1024 dimensions)
echo "▶ tk_company 컬렉션 생성..."
curl -s -X PUT "${QDRANT_URL}/collections/tk_company" \
  -H 'Content-Type: application/json' \
  -d '{
    "vectors": {
      "size": 1024,
      "distance": "Cosine"
    }
  }' | python3 -m json.tool

# 2. tk_company payload 인덱스 생성
echo "▶ tk_company 인덱스 생성..."
for field in year department doc_type created_at; do
  field_type="keyword"
  if [ "$field" = "year" ]; then field_type="integer"; fi
  if [ "$field" = "created_at" ]; then field_type="keyword"; fi

  curl -s -X PUT "${QDRANT_URL}/collections/tk_company/index" \
    -H 'Content-Type: application/json' \
    -d "{
      \"field_name\": \"${field}\",
      \"field_schema\": \"${field_type}\"
    }" | python3 -c "import sys,json; print(f'  {\"${field}\"}: {json.loads(sys.stdin.read()).get(\"status\", \"error\")}')"
done

# 3. chat_memory 인덱스 추가 (username, topic, intent)
echo "▶ chat_memory 인덱스 추가..."
for field in username topic intent; do
  curl -s -X PUT "${QDRANT_URL}/collections/chat_memory/index" \
    -H 'Content-Type: application/json' \
    -d "{
      \"field_name\": \"${field}\",
      \"field_schema\": \"keyword\"
    }" | python3 -c "import sys,json; print(f'  {\"${field}\"}: {json.loads(sys.stdin.read()).get(\"status\", \"error\")}')"
done

# 4. 확인
echo ""
echo "=== 컬렉션 목록 ==="
curl -s "${QDRANT_URL}/collections" | python3 -c "
import sys,json
data = json.loads(sys.stdin.read())
for c in data.get('result',{}).get('collections',[]):
    name = c['name']
    info = json.loads(open('/dev/stdin','r').read()) if False else None
    print(f'  - {name}')
" 2>/dev/null || curl -s "${QDRANT_URL}/collections" | python3 -m json.tool

echo ""
echo "=== tk_company 상세 ==="
curl -s "${QDRANT_URL}/collections/tk_company" | python3 -c "
import sys,json
data = json.loads(sys.stdin.read())
r = data.get('result',{})
print(f'  벡터수: {r.get(\"points_count\",0)}')
print(f'  상태: {r.get(\"status\",\"unknown\")}')
" 2>/dev/null || echo "  (확인 실패)"

echo ""
echo "설정 완료!"
