#!/usr/bin/env python3
"""
北京试点财务表 4m6Ejm 全表复核修正
列映射: N=GMV, O=退款金额, P=GSV, X=订单号, Y=有效订单, Z=渠道归属
"""
import json, time, requests, os

CRED_DIR = "/root/.openclaw/credentials/xiaoxi"
SPREADSHEET_TOKEN = "NoZqsFi47hIOHEt9j8WcfRtbnug"
SHEET_ID = "4m6Ejm"

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 put_values(token, sheet_id, range_str, values):
    url = f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{SPREADSHEET_TOKEN}/values"
    body = {"valueRange": {"range": f"{sheet_id}!{range_str}", "values": values}}
    for attempt in range(3):
        r = requests.put(url, headers={
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json"
        }, json=body, timeout=30)
        result = r.json()
        if result.get("code") == 0:
            return True
        print(f"  Retry {attempt+1}: {result.get('msg','')}")
        time.sleep(1)
    print(f"  FAILED {range_str}")
    return False

def main():
    token = get_token()
    fixes = []

    # === 已退费: Y=0, P→0 (GSV=0) ===
    # r3 陈kelly: status=4, refund=1999
    fixes.append((3, "P", [[0]]))
    # r9 xhx: status=4, refund=1999
    fixes.append((9, "P", [[0]]))
    # r10 跳跳糖: status=4, refund=1999
    fixes.append((10, "P", [[0]]))
    # r25 琪-建筑: status=4, refund=599
    fixes.append((25, "P", [[0]]))

    # === 有效订单: Y=0→1, O→0, P→GSV, 补Z ===
    # r11 Cathy: status=3, 1999, 直购
    fixes.append((11, "N", [["1999"]]))
    fixes.append((11, "O", [[0]]))
    fixes.append((11, "P", [["1999"]]))
    fixes.append((11, "Y", [[1]]))
    fixes.append((11, "Z", [["直购"]]))

    # r12 tingting: status=3, 599, 端内
    fixes.append((12, "N", [["599"]]))
    fixes.append((12, "O", [[0]]))
    fixes.append((12, "P", [["599"]]))
    fixes.append((12, "Y", [[1]]))
    fixes.append((12, "Z", [["端内"]]))

    # r17 MIYU: status=3, 1999, 直购
    fixes.append((17, "N", [["1999"]]))
    fixes.append((17, "O", [[0]]))
    fixes.append((17, "P", [["1999"]]))
    fixes.append((17, "Y", [[1]]))
    fixes.append((17, "Z", [["直购"]]))

    # r18 💋👩👧💋: status=3, 1999, 端内 (已确认)
    fixes.append((18, "O", [[0]]))
    fixes.append((18, "Y", [[1]]))

    # r19 心安就好: status=3, 1999, 直购 (已确认)
    fixes.append((19, "O", [[0]]))
    fixes.append((19, "Y", [[1]]))

    # r20 木木: status=3, 1999, 直购
    fixes.append((20, "N", [["1999"]]))
    fixes.append((20, "O", [[0]]))
    fixes.append((20, "P", [["1999"]]))
    fixes.append((20, "Y", [[1]]))
    fixes.append((20, "Z", [["直购"]]))

    # r21 柏文: 2026010422001499951430352915, status=3, 1999, 端内
    fixes.append((21, "N", [["1999"]]))
    fixes.append((21, "O", [[0]]))
    fixes.append((21, "P", [["1999"]]))
    fixes.append((21, "X", [["2026010422001499951430352915"]]))
    fixes.append((21, "Y", [[1]]))
    fixes.append((21, "Z", [["端内"]]))

    # r22 琉璃仙: status=3, 1999, 直购
    fixes.append((22, "O", [[0]]))
    fixes.append((22, "Y", [[1]]))

    # r24 悦宝爱阳光: status=3, 1999, 直购
    fixes.append((24, "O", [[0]]))
    fixes.append((24, "Y", [[1]]))

    # r27 coco: status=3, 599, 端内
    fixes.append((27, "N", [["599"]]))
    fixes.append((27, "O", [[0]]))
    fixes.append((27, "P", [["599"]]))
    fixes.append((27, "Y", [[1]]))
    fixes.append((27, "Z", [["端内"]]))

    print(f"共 {len(fixes)} 处修正")
    for row, col, vals in fixes:
        rng = f"{col}{row}:{col}{row}"
        if put_values(token, SHEET_ID, rng, vals):
            print(f"  ✓ {rng} = {vals[0]}")
        else:
            print(f"  ✗ {rng} FAILED")
        time.sleep(0.15)

    print("\n=== 修正完成 ===")
    print("\n⚠️ r13 笑看风云(UID 11824): 表内 trade_no=4200002979202510051839311872 DB不存在")
    print("  该账号实际: 4200002979202512297931190703(599, 12/29) + 4200003119202604279087832566(1499, 4/27)")
    print("  请确认正确订单号后手动修正")

if __name__ == "__main__":
    main()
