#!/usr/bin/env python3
"""Update L5-01 + create L5-02 sheets."""
import json, subprocess

S = "BQansBM0eh42xgtaO3OckqDCnTe"
C = "/root/.openclaw/credentials/xiaobian/config.json"

def token():
    aid = subprocess.run(["jq","-r",".apps[0].appId",C],capture_output=True,text=True).stdout.strip()
    asec = subprocess.run(["jq","-r",".apps[0].appSecret",C],capture_output=True,text=True).stdout.strip()
    r = subprocess.run(["curl","-s","-X","POST",
        "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
        "-H","Content-Type: application/json",
        "-d",json.dumps({"app_id":aid,"app_secret":asec})],
        capture_output=True,text=True).stdout
    return json.loads(r)["tenant_access_token"]

def api(m,u,d=None):
    t = token()
    a = ["curl","-s","-X",m,u,"-H",f"Authorization: Bearer {t}","-H","Content-Type: application/json"]
    if d: a.extend(["-d",json.dumps(d,ensure_ascii=False)])
    return json.loads(subprocess.run(a,capture_output=True,text=True).stdout)

# === STEP 1: UPDATE 段① ===
r = api("GET",f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{S}/values/OpBte!A1:D69")
rows = r["data"]["valueRange"]["values"]
print(f"READ 段①: {len(rows)} rows")

# Changes:
# 1. Replace rows 7-16 (idx 6-15) with new 6-row opening
new_open = [
    ["","","Ben","Whoa! It is like a secret base!"],
    ["","","Sue","A secret base? Ben, your mouth is wide open!"],
    ["","","Ben","I can not help it! It is fantastic!"],
    ["","","Vicky","Look. The blue lines go to that big ball."],
    ["","","May","What a beautiful place."],
    ["中互动","","User","He is right. What a fantastic place!"],
]
new_rows = rows[:7] + new_open + rows[16:]
# 2. Fix slope/steep
for rw in new_rows:
    t = rw[3] if len(rw)>3 and rw[3] else ""
    if t and ("slope" in t or "steep" in t):
        old = rw[3]
        rw[3] = t.replace("The slope is too steep.","It can not go down.")
        print(f"FIXED: {old} -> {rw[3]}")

payload = {"valueRange":{"range":f"OpBte!A1:D{len(new_rows)}","values":new_rows}}
wr = api("PUT",f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{S}/values",payload)
print(f"UPDATE 段①: {wr.get('code')} rows={len(new_rows)}")

# === STEP 2: CREATE 段② ===
cr = api("POST",f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{S}/sheets_batch_update",
    {"requests":[{"addSheet":{"properties":{"title":"段② 妈妈的怀抱"}}}]})
sid2 = cr["data"]["replies"][0]["addSheet"]["properties"]["sheetId"]
print(f"CREATED 段② sheet: {sid2}")

# === STEP 3: WRITE 段② ===
seg2 = [
    ["类型","剧情描述","角色名","编剧台词"],
    ["TL","【场景】地下空间·竖井层\n斜坡通道的尽头，巨大的圆形竖井展开在眼前。\n竖井入口被巨型球体堵住——球体表面布满圆形凹槽，每个都和一颗Roball大小完全匹配。","",""],
    ["TL","Roballs围着球体兴奋打转。一颗Roball滚到凹槽前，轻轻跳了进去——完美嵌合。凹槽发出蓝光。","",""],
    ["","更多Roballs跟着跳进自己的位置。球体上的光点一个个亮起——像点亮的星星。","",""],
    ["","","Ben","They all have a home!"],
    ["","","Sue","Each one in its own spot."],
    ["","","May","What a beautiful sight."],
    ["","","Vicky","Everything has a place here."],
    ["","所有Roballs都嵌进凹槽。球体现在是蓝光点组成的满月。","",""],
    ["","","Gaia","At the end of the day, everyone comes home."],
    ["TL","【特效】Gaia举起双臂。球体上的光点同时暴亮——能量从每个凹槽汇入Gaia脚下。\n一个巨大的半透明防护罩从平台升起，向上展开，笼罩整个地下空间。","",""],
    ["TL","沙尘暴扑下来——打在防护罩上，沙子无声滑落。内部平静如止水。","",""],
    ["","","Ben","Whoa! The sand can not get in!"],
    ["","","Sue","We are... inside a bubble?"],
    ["","","Vicky","Not a bubble. A shield."],
    ["","","May","I feel so safe. Like in mom's arms."],
    ["","","Ben","It is fantastic!"],
    ["中互动","","User","This is fantastic. We are all safe here."],
    ["","Gaia缓缓放下手臂。防护罩保持稳定，柔和的蓝光照在每个人脸上。","",""],
    ["","","Vicky","At the end of the day, we are all safe."],
    ["中互动","","User","At the end of the day, we are home."],
    ["TL","【转场】防护罩下的地下空间平静而温暖。\n沙尘暴仍在远处呼啸——但这里，就像躺在妈妈的怀抱里。","",""],
]

payload2 = {"valueRange":{"range":f"{sid2}!A1:D{len(seg2)}","values":seg2}}
w2 = api("PUT",f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{S}/values",payload2)
print(f"WRITE 段②: {w2.get('code')} rows={len(seg2)-1}")

# Verify
v = api("GET",f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{S}/values/{sid2}!A1:D5")
print("VERIFY 段② header:")
for rw in v["data"]["valueRange"]["values"]:
    print(f"  {rw[0] if rw else ''} | {rw[3] if len(rw)>3 else ''}")
