# -*- coding: utf-8 -*-
"""语料分析 v2：分类抽取收益/单量/播放，估算单条视频收益，输出报告"""
import glob, json, os, re, sys
from collections import Counter

sys.stdout.reconfigure(encoding="utf-8")
ROOT = r"D:\Deepseek\tiktok_sea_corpus"
SUB, CMT = os.path.join(ROOT, "subtitles"), os.path.join(ROOT, "comments")
OUT = os.path.join(ROOT, "analysis_report.md")

NUM = r"(\d+(?:\.\d+)?)\s*(万|千|w|W|k|K|亿)?"
EARN = re.compile(r"(赚|收入|收益|佣金|提现|流水|回本|亏|毛利|净利润)")
ORD = re.compile(r"(单|订单|成交|出单)")
VIEW = re.compile(r"(播放|曝光|观看|浏览)")
COST = re.compile(r"(拿货|成本|运费|面单|学费|价格|报价|进价|物流费)")
PERIOD = re.compile(r"(一天|每天|单天|一个月|每月|单月|单条|每条|一条)")

AMT = re.compile(NUM + r"\s*(元|块|人民币|盾|rp|RP|Rp|美元|美金|刀)?")
ORDN = re.compile(NUM + r"\s*(单|订单|成交量)")
VIEWN = re.compile(NUM + r"\s*(播放|播放量|曝光|观看)")

MULT = {"万": 1e4, "w": 1e4, "W": 1e4, "亿": 1e8, "千": 1e3, "k": 1e3, "K": 1e3, None: 1, "": 1}


def val(m):
    return float(m.group(1)) * MULT.get(m.group(2) or "", 1)


def sents(text):
    return [s.strip() for s in re.split(r"[，,。！？!?\n；;]+", text) if 3 < len(s.strip()) < 200]


works = {w["id"]: w for w in json.load(open(os.path.join(ROOT, "_works.json"), encoding="utf-8"))}
per_video = []
for fp in sorted(glob.glob(os.path.join(SUB, "*.txt"))):
    base = os.path.basename(fp)[:-4]
    aid = base.split("_")[-1]
    txt = open(fp, encoding="utf-8").read()
    cmf = os.path.join(CMT, aid + ".json")
    cms = json.load(open(cmf, encoding="utf-8")).get("comments", []) if os.path.exists(cmf) else []
    ctext = "。".join((c.get("text") or "") for c in cms)

    earn, orders, views = [], [], []
    for s in sents(txt) + sents(ctext):
        if COST.search(s) and not EARN.search(s):
            continue
        if EARN.search(s):
            m = AMT.search(s)
            if m:
                earn.append({"text": s[:120], "amount": val(m), "unit": m.group(3) or "", "period": (PERIOD.search(s) or [""])[0]})
        if ORDN.search(s):
            m = ORDN.search(s)
            orders.append({"text": s[:120], "n": val(m), "period": (PERIOD.search(s) or [""])[0]})
        if VIEWN.search(s):
            m = VIEWN.search(s)
            views.append({"text": s[:120], "n": val(m), "period": (PERIOD.search(s) or [""])[0]})

    per_video.append({"id": aid, "author": works.get(aid, {}).get("author", ""),
                      "desc": works.get(aid, {}).get("desc", "")[:70],
                      "digg": works.get(aid, {}).get("digg", 0), "comments": len(cms),
                      "earn": earn, "orders": orders, "views": views})

json.dump(per_video, open(os.path.join(ROOT, "_claims_v2.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)

n_v = len(per_video)
n_earn = sum(1 for r in per_video if r["earn"])
n_ord = sum(1 for r in per_video if r["orders"])
n_view = sum(1 for r in per_video if r["views"])
print(f"视频 {n_v} 条 | 提到收益 {n_earn} | 提到单量 {n_ord} | 提到播放 {n_view}")

cats = Counter()
for r in per_video:
    d = r["desc"]
    if re.search(r"教程|怎么|如何|流程|入门|新手|干货", d): cats["教程/方法"] += 1
    elif re.search(r"报喜|赚|收益|佣金|单量|出单", d): cats["收益/报喜"] += 1
    elif re.search(r"避坑|风险|封|关店|难|谨慎", d): cats["风险/避坑"] += 1
    elif re.search(r"对比|哪个|区别|选择|市场", d): cats["市场对比"] += 1
    else: cats["其他"] += 1
print("内容类型:", cats.most_common())

lines = ["# TikTok 东南亚/印尼带货：抖音语料证据分析\n",
         f"- 语料：{n_v} 条视频（5 个关键词，69 位作者）",
         f"- 提到收益 {n_earn} 条、单量 {n_ord} 条、播放 {n_view} 条\n",
         "## 一、收益相关原句\n", "| 作者 | 原句 |", "|---|---|"]
for r in per_video:
    for e in r["earn"][:3]:
        lines.append(f"| {r['author'][:12]} | {e['text'][:90]} |")
lines += ["\n## 二、单量相关原句\n", "| 作者 | 原句 |", "|---|---|"]
for r in per_video:
    for e in r["orders"][:2]:
        lines.append(f"| {r['author'][:12]} | {e['text'][:90]} |")
lines += ["\n## 三、播放量相关原句\n", "| 作者 | 原句 |", "|---|---|"]
for r in per_video:
    for e in r["views"][:2]:
        lines.append(f"| {r['author'][:12]} | {e['text'][:90]} |")
open(OUT, "w", encoding="utf-8").write("\n".join(lines))
print(f"报告 -> {OUT}")
