#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
export_csv.py — 评分结果 → 本地 CSV 表
================================================

读取 score_inquiry_v3.py 输出的 JSON（含 summary + results 字段），
导出为 UTF-8 with BOM 的 CSV，Excel 双击可直接打开（中文不乱码）。

用法：
    python scripts/export_csv.py outputs/score_real_20260526_220437.json
    python scripts/export_csv.py outputs/score_real_20260526_220437.json --output 询盘分级表.csv

输出字段（按列顺序）：
    1. 询盘ID
    2. 创建日期
    3. 买家国家
    4. 买家名称
    5. 询问产品
    6. 询盘来源（inquiry/chat等）
    7. 接待业务员
    8. 分数（百分制）
    9. 原始分（167分制）
    10. 等级（S/A/B/C/无效）
    11. 关键得分项（关键 reasons 摘要）
    12. Missing字段
    13. 建议下一步
    14. 需人工确认项
"""

import argparse
import csv
import json
import sys
from datetime import datetime
from pathlib import Path


def _truncate(text, n=200):
    """长字段截断，避免单元格爆炸"""
    if not text:
        return ""
    s = str(text)
    return s if len(s) <= n else s[: n - 3] + "..."


def _summarize_reasons(reasons, max_items=5):
    """从 reasons 列表里挑出对得分最有信号的几条"""
    if not reasons:
        return ""
    # 优先保留含 +N / -N / 信号 / 风险 的条目
    weighted = []
    for r in reasons:
        if any(k in r for k in ["+", "-", "信号", "风险", "扣分", "加分"]):
            weighted.append(r)
    picked = weighted[:max_items] if weighted else reasons[:max_items]
    return "; ".join(picked)


def _join_list(items, sep="; "):
    if not items:
        return ""
    if isinstance(items, str):
        return items
    return sep.join(str(x) for x in items)


def export(input_path: Path, output_path: Path):
    with open(input_path, "r", encoding="utf-8") as f:
        data = json.load(f)

    # 支持两种结构：单 dict 含 results / 直接 results 数组
    if isinstance(data, list):
        results = data
        summary = None
    elif isinstance(data, dict):
        if "results" in data:
            results = data["results"]
            summary = data.get("summary")
        elif "scored_inquiries" in data:
            results = data["scored_inquiries"]
            summary = data.get("summary")
        else:
            # 单条评分对象
            results = [data]
            summary = None
    else:
        raise ValueError(f"无法识别的 JSON 结构: {type(data)}")

    if not results:
        print(f"⚠️  输入文件无 results，跳过：{input_path}")
        return 0

    headers = [
        "询盘ID",
        "创建日期",
        "买家国家",
        "买家名称",
        "询问产品",
        "询盘来源",
        "接待业务员",
        "分数(百分制)",
        "原始分(167)",
        "等级",
        "关键得分项",
        "Missing字段",
        "建议下一步",
        "需人工确认项",
    ]

    rows = []
    for r in results:
        rows.append([
            r.get("inquiry_id", ""),
            r.get("received_at", ""),
            r.get("buyer_country", ""),
            r.get("buyer_name", ""),
            _truncate(r.get("product", ""), 100),
            r.get("source", ""),
            r.get("assignee", ""),
            r.get("score", ""),
            r.get("score_raw", ""),
            r.get("grade", ""),
            _truncate(_summarize_reasons(r.get("reasons", [])), 500),
            _truncate(_join_list(r.get("missing_fields", [])), 300),
            _truncate(r.get("next_action", ""), 300),
            _truncate(_join_list(r.get("human_confirmation_items", [])), 300),
        ])

    # UTF-8 with BOM —— Excel 中文不乱码的关键
    with open(output_path, "w", encoding="utf-8-sig", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(headers)
        writer.writerows(rows)

    print(f"✅ 已导出 {len(rows)} 条询盘 → {output_path}")
    if summary:
        gc = summary.get("grade_counts", {})
        print(f"   等级分布: S={gc.get('S', 0)}  A={gc.get('A', 0)}  B={gc.get('B', 0)}  C={gc.get('C', 0)}  无效={gc.get('无效', 0)}")
        if summary.get("high_priority_count"):
            print(f"   ⭐ 高优先级: {summary['high_priority_count']} 条")
    return len(rows)


def main():
    ap = argparse.ArgumentParser(description="评分结果导出本地 CSV（Excel 双击可开）")
    ap.add_argument("input", type=str, help="score_*.json 文件路径")
    ap.add_argument("--output", "-o", type=str, default=None, help="输出 CSV 路径（默认输出到 outputs/询盘分级表_<时间戳>.csv）")
    args = ap.parse_args()

    inp = Path(args.input)
    if not inp.exists():
        print(f"❌ 输入文件不存在: {inp}", file=sys.stderr)
        sys.exit(1)

    if args.output:
        out = Path(args.output)
    else:
        ts = datetime.now().strftime("%Y%m%d_%H%M%S")
        out_dir = inp.parent if inp.parent.name == "outputs" else Path("outputs")
        out_dir.mkdir(parents=True, exist_ok=True)
        out = out_dir / f"询盘分级表_{ts}.csv"

    out.parent.mkdir(parents=True, exist_ok=True)
    n = export(inp, out)
    if n == 0:
        sys.exit(2)


if __name__ == "__main__":
    main()
