"""스레드 분리 및 덤프 스크립트 — wiki 정제 전처리용."""
from __future__ import annotations

import json
import sys
from pathlib import Path

# insuwiki 모듈 경로 추가
sys.path.insert(0, "/home/jay/projects/insuwiki/scripts")

from kakao_knowledge.knowledge_extractor import _split_into_threads, _mask_phone
from kakao_knowledge.models import ChatMessage


def main() -> None:
    parsed_path = Path("/tmp/parsed.json")
    raw = json.loads(parsed_path.read_text(encoding="utf-8"))

    messages = [ChatMessage(**m) for m in raw.get("messages", [])]
    source_chat = raw.get("header", {}).get("chat_name", "")

    threads = _split_into_threads(messages)

    print(f"총 스레드 수: {len(threads)}")
    print(f"채팅방: {source_chat}")

    # 각 스레드를 JSON으로 덤프
    thread_data = []
    for i, thread in enumerate(threads):
        msgs = []
        for m in thread.messages:
            msgs.append({
                "user": m.user,
                "content": _mask_phone(m.content),
                "date": m.date,
                "time": m.time,
            })
        thread_data.append({
            "index": i,
            "msg_count": len(thread.messages),
            "has_question_tag": thread.has_question_tag,
            "start_time": thread.start_time,
            "messages": msgs,
        })

    output_path = Path("/tmp/threads.json")
    output_path.write_text(
        json.dumps(thread_data, ensure_ascii=False, indent=2),
        encoding="utf-8",
    )
    print(f"스레드 데이터 저장: {output_path}")

    # 통계 출력
    tagged = sum(1 for t in thread_data if t["has_question_tag"])
    print(f"#궁금증 태그 스레드: {tagged}개")
    print(f"태그 없는 스레드: {len(thread_data) - tagged}개")

    # 메시지 수 분포
    msg_counts = [t["msg_count"] for t in thread_data]
    print(f"스레드당 메시지 수 — min:{min(msg_counts)}, max:{max(msg_counts)}, avg:{sum(msg_counts)/len(msg_counts):.1f}")


if __name__ == "__main__":
    main()
