from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional

from pydantic import BaseModel

from .models import ChatMessage  # noqa: F401 (재export 포함)


class InsightType(str, Enum):
    QA = "qa"                                                      # 질문 + 전문가 답변
    EXPERT_OPINION = "expert_opinion"                              # 경험 공유 ("제 경험상...", "실무에서는...")
    CASE_ANALYSIS = "case_analysis"                                # 실제 보험 사고/보상 사례 공유
    REGULATION_INTERPRETATION = "regulation_interpretation"        # 약관 조항 해석/논쟁
    PRACTICAL_TIP = "practical_tip"                                # 설계사 영업/업무 노하우
    REGULATION_CHANGE = "regulation_change"                        # 법/규정/고시 변경 정보
    WARNING = "warning"                                            # "이런 건 주의하세요" 유형


# 15+ 카테고리 정의
CATEGORIES: dict[str, list[str]] = {
    "보상": ["자동차", "일반", "장기"],
    "고지의무": [],
    "약관해석": [],
    "상품비교": [],
    "언더라이팅": [],
    "민원처리": [],
    "손해사정": [],
    "의학지식": [],
    "세금/절세": [],
    "법률/판례": [],
    "영업노하우": [],
    "고객관리": [],
    "GA운영": [],
    "수수료체계": [],
    "디지털/IT": [],
    "기타": [],
}

# 모든 카테고리를 flat list로
ALL_CATEGORIES: list[str] = []
for _cat, _subs in CATEGORIES.items():
    if _subs:
        for _sub in _subs:
            ALL_CATEGORIES.append(f"{_cat}/{_sub}")
    else:
        ALL_CATEGORIES.append(_cat)


class InsightV2(BaseModel):
    """v2 인사이트 모델"""

    id: str                           # "insight-001"
    title: str                        # 핵심 주제 (50자 이내)
    type: InsightType                 # 7가지 유형 중 하나
    category: str                     # 확장된 카테고리
    summary: str                      # 핵심 내용 요약 (200자)
    key_points: list[str]             # 핵심 포인트 리스트
    expert: str = ""                  # 전문가 식별
    confidence: str = "medium"        # high/medium/low
    related_topics: list[str] = []    # 관련 주제 키워드
    tags: list[str] = []              # #태그 리스트
    source_date: str = ""             # "2025-12-03"
    source_chat: str = ""             # 채팅방 이름
    raw_thread: list[str] = []        # 원본 대화
    participants: list[str] = []      # 참여자 목록

    # Phase 1에서 사용할 Q&A 호환 필드 (선택적)
    question: str = ""
    answer: str = ""


@dataclass
class ThreadV2:
    """개선된 스레드 (주제 기반 분리 지원)"""

    messages: list[ChatMessage] = field(default_factory=list)
    start_time: str = ""
    topic_label: str = ""                               # LLM이 판별한 주제 라벨
    has_insight: Optional[bool] = None                  # Stage 1에서 판별
    insight_types: list[str] = field(default_factory=list)  # Stage 1에서 판별한 유형들


@dataclass
class Stage1Result:
    """Stage 1 (Haiku) 필터링 결과"""

    thread: ThreadV2
    has_insight: bool
    insight_types: list[str]    # 예: ["qa", "expert_opinion"]
    noise_reason: str = ""      # has_insight=False일 때 사유


@dataclass
class BatchProgress:
    """배치 처리 진행 상태"""

    total_threads: int = 0
    processed_threads: int = 0
    insights_found: int = 0
    noise_filtered: int = 0
    errors: int = 0
