"""
alibaba-inquiry-analyst / cleaner.py
=====================================
对话数据统计模块。

注意：说话人识别已通过 DOM 结构实现（detail_scraper.py），
本模块仅保留统计计算功能。
"""

from __future__ import annotations

from datetime import datetime

# 说话人类型
SPEAKER_BUYER = "buyer"
SPEAKER_SELLER = "seller"
SPEAKER_BOT = "bot"


def is_today_time(text: str) -> bool:
    """创建时间只有 HH:MM（无日期）= 今日"""
    import re
    if re.search(r'\d{4}-\d{1,2}-\d{1,2}', text):
        return False
    return bool(re.search(r'\d{1,2}:\d{2}', text))


def compute_stats(messages: list[dict], unreplied_threshold_hours: int = 1) -> dict:
    """
    计算对话统计数据。

    返回：
    - message_count: 消息总数
    - buyer_msg_count: 买家消息数
    - seller_msg_count: 业务员消息数
    - bot_msg_count: 机器人消息数
    - first_seller_response: 业务员首次回复时间戳（或 None）
    - last_buyer_msg: 买家最后消息时间戳（或 None）
    - last_msg_speaker: 最后一条消息的说话人
    - last_msg_time: 最后一条消息的时间戳（或 None）
    - unreplied: 是否未回复（最后一条为买家消息且等待超过阈值）
    """
    if not messages:
        return {
            "message_count": 0,
            "buyer_msg_count": 0,
            "seller_msg_count": 0,
            "bot_msg_count": 0,
            "first_seller_response": None,
            "last_buyer_msg": None,
            "last_msg_speaker": None,
            "last_msg_time": None,
            "unreplied": False
        }

    def message_time(message: dict) -> datetime:
        try:
            return datetime.strptime(message.get("timestamp"), "%Y-%m-%d %H:%M")
        except (ValueError, TypeError):
            return datetime.min

    # DOM order is newest-first; use it to break same-minute timestamp ties.
    ordered_messages = [
        message for index, message in sorted(
            enumerate(messages),
            key=lambda item: (message_time(item[1]), -item[0])
        )
    ]
    buyer_msgs = [m for m in ordered_messages if m.get("speaker") == SPEAKER_BUYER]
    seller_msgs = [m for m in ordered_messages if m.get("speaker") == SPEAKER_SELLER]
    bot_msgs = [m for m in ordered_messages if m.get("speaker") == SPEAKER_BOT]

    # 业务员首次回复：排除 bot，取 seller 第一条
    first_seller_response = seller_msgs[0].get("timestamp") if seller_msgs else None
    last_buyer_msg = buyer_msgs[-1].get("timestamp") if buyer_msgs else None
    last_msg_speaker = ordered_messages[-1].get("speaker") if ordered_messages else None
    last_msg_time = ordered_messages[-1].get("timestamp") if ordered_messages else None

    # 未回复判断：最后一条为买家消息且等待超过阈值
    unreplied = False
    if last_msg_speaker == SPEAKER_BUYER and last_buyer_msg:
        try:
            msg_time = datetime.strptime(last_buyer_msg, "%Y-%m-%d %H:%M")
            time_diff = datetime.now() - msg_time
            unreplied = time_diff.total_seconds() > (unreplied_threshold_hours * 3600)
        except (ValueError, TypeError):
            unreplied = False

    return {
        "message_count": len(messages),
        "buyer_msg_count": len(buyer_msgs),
        "seller_msg_count": len(seller_msgs),
        "bot_msg_count": len(bot_msgs),
        "first_seller_response": first_seller_response,
        "last_buyer_msg": last_buyer_msg,
        "last_msg_speaker": last_msg_speaker,
        "last_msg_time": last_msg_time,
        "unreplied": unreplied
    }
