from __future__ import annotations

"""
alibaba-inquiry-analyst / wechat_formatter.py
==========================================
微信格式输出转换器。

将JSON数据转换为适合微信发送的纯文本格式。
模块结构与 references/report_template.md 保持一致：
  ① 总览（统计指标 + 来源市场 + 负责人）
  ② 全部询盘摘要（逐条一句话）
"""

from datetime import datetime
from typing import Any

from output import build_metrics


FROZEN_BUSINESS_OPPORTUNITY_LABEL = "已冻结"


def _buyer_market_label(inq: dict[str, Any]) -> str:
    buyer = (inq.get("buyer_name") or "未知买家").strip()
    level = (inq.get("user_level") or "").strip()
    country = (inq.get("country") or "").strip()
    meta = "｜".join(part for part in (level, country) if part)
    return f"{buyer}（{meta}）" if meta else buyer


def _status_label(inq: dict[str, Any]) -> str:
    if not _has_valid_detail(inq):
        return ""

    stats = (inq.get("detail") or {}).get("stats", {})
    if stats.get("unreplied", False):
        return "未回复"

    if stats.get("last_msg_speaker") == "buyer" and stats.get("last_msg_time"):
        return "待回复"

    return ""


def _product_ids_label(inq: dict[str, Any]) -> str:
    ids = inq.get("buyer_product_ids") or inq.get("product_ids") or []
    if not ids:
        detail = inq.get("detail") or {}
        ids = [
            card.get("product_id")
            for card in detail.get("product_cards") or []
            if card.get("product_id")
        ]

    deduped = []
    seen = set()
    for value in ids:
        product_id = str(value or "").strip()
        if not product_id or product_id in seen:
            continue
        seen.add(product_id)
        deduped.append(product_id)

    if not deduped:
        return ""
    if len(deduped) <= 3:
        return ", ".join(deduped)
    return f"{', '.join(deduped[:3])} +{len(deduped) - 3}"


def _format_inquiry_line(inq: dict[str, Any], idx: int) -> list[str]:
    buyer_label = _buyer_market_label(inq)
    product = (inq.get("product") or "未指定产品")[:20]
    assignee = (inq.get("assignee") or "未分配").strip()
    created = inq.get("create_time", "-")
    first_reply = inq.get("first_reply_time") or "-"
    stats = (inq.get("detail") or {}).get("stats", {})
    last_update = stats.get("last_msg_time") or inq.get("update_time") or "-"

    tags = []
    status = _status_label(inq)
    if status:
        tags.append(status)
    product_ids = _product_ids_label(inq)
    if product_ids:
        tags.append(f"产品ID: {product_ids}")
    if assignee:
        tags.append(f"负责人: {assignee}")

    lines = [f"{idx}. {buyer_label} | {product}"]
    if tags:
        lines.append(f"   {' | '.join(tags)}")
    lines.append(f"   📅{created}  💬{first_reply}  🔄{last_update}")
    return lines


def format_wechat_report(data: dict) -> str:
    """
    将询盘数据格式化为微信友好的纯文本报告。

    参数：
    - data: output.py生成的JSON数据

    返回：适合微信发送的纯文本字符串
    """
    inquiries = data.get("inquiries", [])
    if not inquiries:
        return "【阿里国际站询盘】\n\n今日暂无询盘数据。"

    lines = []
    date_str = data.get("date", datetime.now().strftime("%Y-%m-%d"))
    scope_desc = data.get("scope_desc", "今日询盘")

    # 标题
    lines.append(f"【阿里国际站每日询盘】{date_str}")
    lines.append("")

    # ① 总览
    lines.append("━━━━━━━━━━━━━━━━━━")
    lines.append(f"① 总览（{scope_desc}）")
    lines.append("━━━━━━━━━━━━━━━━━━")

    total = len(inquiries)
    metrics = data.get("metrics") or build_metrics(inquiries)

    # 三态统计：已回复 / 未回复 / 未知
    has_detail_inquiries = [i for i in inquiries if _has_valid_detail(i)]
    unknown_inquiries = [i for i in inquiries if not _has_valid_detail(i)]

    unreplied = sum(1 for i in has_detail_inquiries
                    if (i.get("detail") or {}).get("stats", {}).get("unreplied"))
    replied = len(has_detail_inquiries) - unreplied
    unknown = len(unknown_inquiries)

    # 统计产品种类、国家、负责人、用户等级
    products = set()
    countries = set()
    assignees = set()
    level_counts = {}
    for inq in inquiries:
        if inq.get("product"):
            products.add(inq["product"])
        if inq.get("country"):
            countries.add(inq["country"])
        if inq.get("assignee"):
            assignees.add(inq["assignee"])
        lvl = inq.get("user_level", "") or ""
        if not lvl:
            lvl = "未识别"
        elif lvl == "L0":
            lvl = "L0（无等级）"
        level_counts[lvl] = level_counts.get(lvl, 0) + 1

    lines.append(f"询盘数量: {total}条")
    lines.append(
        "询盘人数: {inquiry_buyer_count} | 询盘个数: {inquiry_count} | TM咨询人数: {tm_buyer_count} | 商品商机量: {business_opportunity_count}".format(
            inquiry_buyer_count=metrics.get("inquiry_buyer_count", 0),
            inquiry_count=metrics.get("inquiry_count", 0),
            tm_buyer_count=metrics.get("tm_buyer_count", 0),
            business_opportunity_count=FROZEN_BUSINESS_OPPORTUNITY_LABEL,
        )
    )
    lines.append(f"已回复: {replied}条 | 未回复: {unreplied}条 | 未知: {unknown}条")
    lines.append(f"涉及产品种类: {len(products)}种")
    # 用户等级分布
    level_parts = [f"{k} {v}条" for k, v in sorted(level_counts.items())]
    lines.append(f"用户等级分布: {' | '.join(level_parts)}")
    lines.append(f"来源国家/地区: {len(countries)}个")
    if countries:
        # 按出现次数排序，取前 5 个
        country_counts = {}
        for inq in inquiries:
            c = inq.get("country", "")
            if c:
                country_counts[c] = country_counts.get(c, 0) + 1
        top = sorted(country_counts.items(), key=lambda x: -x[1])[:5]
        lines.append(f"主要来源市场: {', '.join(c for c, _ in top)}")
    lines.append(f"负责业务员: {', '.join(assignees) if assignees else '未分配'}")
    lines.append("")

    # ② 全部询盘摘要
    lines.append("━━━━━━━━━━━━━━━━━━")
    lines.append("② 全部询盘摘要")
    lines.append("━━━━━━━━━━━━━━━━━━")
    for idx, inq in enumerate(inquiries, 1):
        lines.extend(_format_inquiry_line(inq, idx))

    lines.append("")
    lines.append("━━━━━━━━━━━━━━━━━━")
    lines.append(f"⏰ 生成时间: {data.get('generated_at', datetime.now().strftime('%H:%M'))}")

    return "\n".join(lines)


def _has_valid_detail(inq: dict) -> bool:
    """
    判断询盘是否有有效详情数据。

    无效详情的情况：
    - detail 为 None
    - detail_skipped = True
    - scrape_status 为 error 开头
    """
    if inq.get("detail_skipped"):
        return False
    detail = inq.get("detail")
    if not detail:
        return False
    status = inq.get("scrape_status", "")
    if isinstance(status, str) and status.startswith("error"):
        return False
    return True


def format_wechat_summary(data: dict) -> str:
    """
    格式化简短摘要（适合快速浏览）。

    当询盘数量较多时，先发送摘要，详细报告作为后续消息。
    """
    inquiries = data.get("inquiries", [])
    total = len(inquiries)

    if total == 0:
        return "【阿里国际站】今日暂无询盘"

    # 三态统计
    metrics = data.get("metrics") or build_metrics(inquiries)
    has_detail_inquiries = [i for i in inquiries if _has_valid_detail(i)]
    unknown_inquiries = [i for i in inquiries if not _has_valid_detail(i)]

    unreplied = sum(1 for i in has_detail_inquiries
                    if (i.get("detail") or {}).get("stats", {}).get("unreplied"))
    replied = len(has_detail_inquiries) - unreplied
    unknown = len(unknown_inquiries)

    lines = [
        f"【阿里国际站每日简报】{data.get('date', '')}",
        "",
        f"📊 总计: {total}条询盘 | 已回复: {replied} | 未回复: {unreplied} | 未知: {unknown}",
        "询盘人数: {inquiry_buyer_count} | 询盘个数: {inquiry_count} | TM咨询人数: {tm_buyer_count} | 商品商机量: {business_opportunity_count}".format(
            inquiry_buyer_count=metrics.get("inquiry_buyer_count", 0),
            inquiry_count=metrics.get("inquiry_count", 0),
            tm_buyer_count=metrics.get("tm_buyer_count", 0),
            business_opportunity_count=FROZEN_BUSINESS_OPPORTUNITY_LABEL,
        ),
    ]

    if unreplied > 0:
        lines.append("")
        lines.append("⚠️ 未回复询盘需要跟进！")

    return "\n".join(lines)
