# -*- coding: utf-8 -*-
"""300 个号的矩阵：2027 全年毛佣金模拟 + 成本/净利测算"""
import math, random, statistics as st, sys, json

sys.stdout.reconfigure(encoding="utf-8")
random.seed(11)
TRIALS = 2000
ACCOUNTS = 300

SEASON = [1.00, 0.90, 1.00, 1.00, 1.00, 1.25, 1.00, 1.00, 1.05, 1.10, 1.80, 1.15]
BOOST, HAIRCUT = 1.25, 0.80

# 矩阵里质量分布更差：70% C / 30% D
PROFILES = {
    "C": {"p": 0.70, "posts": 5, "class": [(0.60, 0.04, 2.0, 0.38), (0.28, 0.18, 2.0, 0.70), (0.09, 0.80, 1.9, 1.00), (0.03, 5.00, 1.7, 1.00)]},
    "D": {"p": 0.30, "posts": 8, "class": [(0.42, 0.12, 2.0, 0.55), (0.36, 0.45, 2.0, 0.85), (0.17, 1.80, 1.9, 1.00), (0.05, 9.00, 1.7, 1.00)]},
}


def pick(cls):
    r = random.random(); cum = 0
    for p, med, sig, act in cls:
        cum += p
        if r <= cum:
            return med, sig, act
    return cls[-1][1], cls[-1][2], cls[-1][3]


def account_year(prof):
    med, sig, act = pick(prof["class"])
    posts = prof["posts"]
    prev1 = prev2 = 0.0
    alive = 1.0
    total = 0.0
    for m in range(12):
        growth = 1.0 + 0.15 * min(m, 5)
        n = posts * 30 * act
        new = sum(random.lognormvariate(math.log(max(med * growth, 1e-6)), sig) for _ in range(int(n)))
        rev = (0.60 * new + 0.25 * prev1 + 0.15 * prev2) * SEASON[m] * BOOST * HAIRCUT * alive
        total += rev
        prev2, prev1 = prev1, new
        if random.random() < 0.06:
            alive *= 0.3
    return total


def pct(xs, p):
    xs = sorted(xs); return xs[min(int(len(xs) * p), len(xs) - 1)]


if __name__ == "__main__":
    # 预采样单号年收益
    c_samp = [account_year(PROFILES["C"]) for _ in range(6000)]
    d_samp = [account_year(PROFILES["D"]) for _ in range(6000)]
    print(f"单号年收益（矩阵口径）：C 中位 {st.median(c_samp):,.0f} / 均值 {st.mean(c_samp):,.0f}；"
          f"D 中位 {st.median(d_samp):,.0f} / 均值 {st.mean(d_samp):,.0f}")

    totals = []
    for _ in range(TRIALS):
        # 平台级共同风险：20% 概率遭遇一次大规模治理（全矩阵打 5 折），另有 ±25% 的年度波动
        shared = random.lognormvariate(0, 0.25)
        if random.random() < 0.20:
            shared *= 0.5
        s = 0.0
        for _a in range(ACCOUNTS):
            s += random.choice(c_samp) if random.random() < PROFILES["C"]["p"] else random.choice(d_samp)
        totals.append(s * shared)

    print("\n=== 300 个号｜2027 全年毛佣金 ===")
    print(f"均值 {st.mean(totals):,.0f} | 中位 {st.median(totals):,.0f} | P25 {pct(totals,.25):,.0f} | "
          f"P75 {pct(totals,.75):,.0f} | P90 {pct(totals,.9):,.0f}")
    print(f"折合单号：中位 {st.median(totals)/ACCOUNTS:,.0f} 元/号/年 | 均值 {st.mean(totals)/ACCOUNTS:,.0f}")

    # ---- 成本 ----
    videos = ACCOUNTS * (PROFILES["C"]["p"] * PROFILES["C"]["posts"] + PROFILES["D"]["p"] * PROFILES["D"]["posts"]) * 360
    editors = videos / 12000            # 每人每天 40 条 × 300 天
    labor = editors * 72000             # 6k/月
    accounts_cost = ACCOUNTS * 100
    software = 120000
    mgmt = 2 * 120000
    cost = labor + accounts_cost + software + mgmt
    print(f"\n=== 成本测算（年产 {videos:,.0f} 条）===")
    print(f"剪辑：需 {editors:.0f} 人 × 7.2 万 = {labor/1e4:,.0f} 万")
    print(f"账号：300 × 100 = {accounts_cost/1e4:,.1f} 万 | 软件/代理 12 万 | 管理 2 人 24 万")
    print(f"合计成本 ≈ {cost/1e4:,.0f} 万/年")
    print(f"净利（中位口径）≈ {(st.median(totals)-cost)/1e4:,.0f} 万；净利（均值口径）≈ {(st.mean(totals)-cost)/1e4:,.0f} 万")
    print(f"单条视频平均佣金：{st.mean(totals)/videos:.2f} 元；单条成本：{cost/videos:.2f} 元")

    json.dump({"gross_mean": st.mean(totals), "gross_median": st.median(totals),
               "p25": pct(totals, .25), "p75": pct(totals, .75), "p90": pct(totals, .9),
               "cost": cost, "videos": videos},
              open(r"D:\Deepseek\douyin_fengdaquan\_matrix_result.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1)
