#!/usr/bin/env python3
"""重写投放日报体系公式，建立数据引用链：
📊 每日线索 → 销转总览(C) + 过程数据(C)
关键投放数据 → 销转总览(I)
订单汇总 → 销转总览(F/G/D)
销转总览 → 投放日报
过程数据 → 投放日报
"""

import json, requests, os, time

CRED_DIR = "/root/.openclaw/credentials/xiaoxi"
SPREADSHEET_TOKEN = "NoZqsFi47hIOHEt9j8WcfRtbnug"

def get_token():
    with open(os.path.join(CRED_DIR, "config.json")) as f:
        cfg = json.load(f)
    resp = requests.post(
        "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
        json={"app_id": cfg["apps"][0]["appId"], "app_secret": cfg["apps"][0]["appSecret"]},
        timeout=15)
    return resp.json()["tenant_access_token"]

def write_formulas(sheet_id, range_str, values):
    resp = requests.put(
        f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{SPREADSHEET_TOKEN}/values",
        headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
        json={"valueRange": {"range": range_str, "values": values}},
        params={"valueInputOption": "USER_ENTERED"},
        timeout=60)
    result = resp.json()
    ok = result.get("code") == 0
    if not ok:
        print(f"  ❌ {range_str}: code={result.get('code')} msg={result.get('msg')}")
    else:
        print(f"  ✅ {range_str}")
    return ok

token = get_token()

# ============================================================
# 1. 销转总览 (3fR34k) — C列线索 + F列GMV
# ============================================================
print("=== 1. 销转总览 C列(线索) ===")

clue_formulas = [
    # 3月
    ['=SUMIFS(\'📊 每日线索\'!F:F,\'📊 每日线索\'!A:A,"3月*")'],  # 合计
    ['=SUMIFS(\'📊 每日线索\'!B:B,\'📊 每日线索\'!A:A,"3月*")'],  # 小龙
    ['=SUMIFS(\'📊 每日线索\'!D:D,\'📊 每日线索\'!A:A,"3月*")'],  # Bob
    ['=SUMIFS(\'📊 每日线索\'!E:E,\'📊 每日线索\'!A:A,"3月*")'],  # Tom
    # 4月
    ['=SUMIFS(\'📊 每日线索\'!F:F,\'📊 每日线索\'!A:A,"4月*")'],  # 合计
    ['=SUMIFS(\'📊 每日线索\'!B:B,\'📊 每日线索\'!A:A,"4月*")'],  # 小龙
    ['=SUMIFS(\'📊 每日线索\'!C:C,\'📊 每日线索\'!A:A,"4月*")'],  # 吴迪
    ['=SUMIFS(\'📊 每日线索\'!D:D,\'📊 每日线索\'!A:A,"4月*")'],  # Bob
    ['=SUMIFS(\'📊 每日线索\'!E:E,\'📊 每日线索\'!A:A,"4月*")'],  # Tom
    # 5月
    ['=SUMIFS(\'📊 每日线索\'!F:F,\'📊 每日线索\'!A:A,"5月*")'],  # 合计
    ['=SUMIFS(\'📊 每日线索\'!B:B,\'📊 每日线索\'!A:A,"5月*")'],  # 小龙
    ['=SUMIFS(\'📊 每日线索\'!C:C,\'📊 每日线索\'!A:A,"5月*")'],  # 吴迪
    ['=SUMIFS(\'📊 每日线索\'!D:D,\'📊 每日线索\'!A:A,"5月*")'],  # Bob
    ['=SUMIFS(\'📊 每日线索\'!E:E,\'📊 每日线索\'!A:A,"5月*")'],  # Tom
    # 6月
    ['=SUMIFS(\'📊 每日线索\'!F:F,\'📊 每日线索\'!A:A,"6月*")'],  # 合计
    ['=SUMIFS(\'📊 每日线索\'!B:B,\'📊 每日线索\'!A:A,"6月*")'],  # 小龙
    ['=SUMIFS(\'📊 每日线索\'!C:C,\'📊 每日线索\'!A:A,"6月*")'],  # 吴迪
    ['=SUMIFS(\'📊 每日线索\'!D:D,\'📊 每日线索\'!A:A,"6月*")'],  # Bob
    ['=SUMIFS(\'📊 每日线索\'!E:E,\'📊 每日线索\'!A:A,"6月*")'],  # Tom
]
write_formulas("3fR34k", "3fR34k!C2:C20", clue_formulas)

print("=== 1b. 销转总览 F列(GMV) ===")
sales_order = ["合计", "小龙", "Bob", "Tom",
               "合计", "小龙", "吴迪", "Bob", "Tom",
               "合计", "小龙", "吴迪", "Bob", "Tom",
               "合计", "小龙", "吴迪", "Bob", "Tom"]
months = ["3月"]*4 + ["4月"]*5 + ["5月"]*5 + ["6月"]*5

gmv_formulas = []
for sales, month in zip(sales_order, months):
    if sales == "合计":
        f = f'=SUMIFS(\'订单汇总\'!G:G,\'订单汇总\'!B:B,"{month}*")'
    else:
        f = f'=SUMIFS(\'订单汇总\'!G:G,\'订单汇总\'!A:A,"{sales}",\'订单汇总\'!B:B,"{month}*")'
    gmv_formulas.append([f])
write_formulas("3fR34k", "3fR34k!F2:F20", gmv_formulas)

# ============================================================
# 2. 过程数据 (3aOvV6) — C列线索总数
# ============================================================
print("=== 2. 过程数据 C列(线索总数) ===")

proc_sales = ["合计", "小龙", "Bob", "Tom",
              "合计", "小龙", "吴迪", "Bob", "Tom",
              "合计", "小龙", "吴迪", "Bob", "Tom",
              "合计", "小龙", "吴迪", "Bob", "Tom"]
proc_months = ["3月"]*4 + ["4月"]*5 + ["5月"]*5 + ["6月"]*5

proc_c = []
for sales, month in zip(proc_sales, proc_months):
    col_map = {"合计": "F", "小龙": "B", "吴迪": "C", "Bob": "D", "Tom": "E"}
    col = col_map[sales]
    f = f'=SUMIFS(\'📊 每日线索\'!{col}:{col},\'📊 每日线索\'!A:A,"{month}*")'
    proc_c.append([f])
write_formulas("3aOvV6", "3aOvV6!C2:C20", proc_c)

# ============================================================
# 3. 投放日报 (31Pt60) — 整月汇总 + 销转明细
# ============================================================
print("=== 3. 投放日报 — 整月汇总 ===")

summary_refs = {
    3: {"zt": 2, "param": 2},
    4: {"zt": 6, "param": 3},
    5: {"zt": 11, "param": 4},
}

for month, ref in summary_refs.items():
    zr = ref["zt"]
    pr = ref["param"]
    row_num = month  # 3→row3, 4→row4, 5→row5
    formulas = [[
        f"='📊 销转总览'!I{zr}",   # B: 投放消耗
        f"='📊 销转总览'!L{zr}",   # C: 总成本
        f"='📊 销转总览'!C{zr}",   # D: 线索
        f"='📊 参数'!B{pr}",       # E: 线索成本
        f"='📊 销转总览'!F{zr}",   # F: GMV
        f"='📊 销转总览'!H{zr}",   # G: GSV
        f"='📊 销转总览'!M{zr}",   # H: ROI
        f"='📊 销转总览'!E{zr}",   # I: 转化率
    ]]
    write_formulas("31Pt60", f"31Pt60!B{row_num}:I{row_num}", formulas)

print("=== 3b. 投放日报 — 销转明细 ===")

detail_map = [
    (13, 2, 2),   # 3月合计
    (14, 3, 3),   # 3月小龙
    (15, 4, 4),   # 3月Bob
    (16, 5, 5),   # 3月Tom
    (17, 6, 6),   # 4月合计
    (18, 7, 7),   # 4月小龙
    (19, 8, 8),   # 4月吴迪
    (20, 9, 9),   # 4月Bob
    (21, 10, 10), # 4月Tom
    (22, 11, 11), # 5月合计
    (23, 12, 12), # 5月小龙
    (24, 13, 13), # 5月吴迪
    (25, 14, 14), # 5月Bob
    (26, 15, 15), # 5月Tom
]

for rb_row, zt_row, proc_row in detail_map:
    formulas = [[
        f"='📊 销转总览'!C{zt_row}",   # C: 月线索
        f"='📊 销转总览'!D{zt_row}",   # D: 订单
        f"='📊 销转总览'!F{zt_row}",   # E: GMV
        f"='📊 销转总览'!E{zt_row}",   # F: 转化率
        f"='📊 过程数据'!D{proc_row}",  # G: 拿号率
        f"='📊 过程数据'!F{proc_row}",  # H: 注册率
        f"='📊 过程数据'!H{proc_row}",  # I: 首课率
        f"='📊 过程数据'!X{proc_row}",  # J: 5课率
    ]]
    write_formulas("31Pt60", f"31Pt60!C{rb_row}:J{rb_row}", formulas)

print("\n✅ 全部公式写入完成！")
