#!/usr/bin/env python3
"""Generate G列 component configs for L1-S2-U17-L5 笨蛋坏蛋？(v2 — updated row numbers)"""
import subprocess, json

APP_SECRET = json.load(open('/root/.openclaw/credentials/xiaoyan/config.json'))['apps'][0]['appSecret']
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": "cli_a931175d41799cc7", "app_secret": APP_SECRET})],
    capture_output=True, text=True)
TOKEN = json.loads(r.stdout)['tenant_access_token']
SST = 'DCcKsLbrmhfXgrtB7N2c9GA4ntf'
SID = 'wMQVyV'

# ===== 对话朗读 (6) =====
# ===== 对话挖空 (3) =====
# ===== 互动 (7) =====
# ===== 核心互动-口语 (1) =====

configs = [
    # --- 对话朗读 ---
    (14, """【任务标题】机器人在指向什么？
【资源配置】图片时机：无
【情境引入】Ben : It points at something!
【互动内容】It points at the blackboard.（朗读）
【后置对话】Ben : That's right. And it also talks a lot!"""),

    (29, """【任务标题】机器人在自言自语吗？
【资源配置】图片时机：无
【情境引入】Robot : Bip bop! Bip bop bip!
【互动内容】Hmm, it talks to itself.（朗读）
【后置对话】Ben : ...in a language we can't understand!"""),

    (42, """【任务标题】机器人为什么走不动？
【资源配置】图片时机：无
【情境引入】Ben : What is it doing now?
【互动内容】But a lot of our desks block it.（朗读）
【后置对话】Ben : Yes! The desks are in its way."""),

    (66, """【任务标题】我们该怎么办？
【资源配置】图片时机：无
【情境引入】Ben : Fine. You're right. What should we do now?
【互动内容】Let's talk to it!（朗读）
【后置对话】Ben : Talk to it? But it's a robot!"""),

    (77, """【任务标题】你能听懂机器人吗？
【资源配置】图片时机：无
【情境引入】Robot : Bip bop!
【互动内容】We can't understand it.（朗读）
【后置对话】Ben : What's your name?"""),

    (89, """【任务标题】你明白了什么？
【资源配置】图片时机：无
【情境引入】Robot points at the number "11" on its chest.
【互动内容】Oh, I understand!（朗读）
【后置对话】Ben : You understand? Tell me!"""),

    # --- 对话挖空 ---
    (96, """【任务标题】指出机器人的名字
【资源配置】无
【情境引入】Ben : Wow, it is pointing at itself!
【互动内容】It ___ to its name.（音频）
选项1：points（正确）
选项2：talks
【互动反馈】
正确 Ben : Yes! It points to its name. Its name is 11!
错误 Ben : What is the robot doing? Think again.
【后置对话】User : Its name is 11! We call it 11!"""),

    (119, """【任务标题】机器人想做什么？
【资源配置】无
【情境引入】Robot draws on the blackboard.
【互动内容】Oh! It tries to ___ to us.（音频）
选项1：talk（正确）
选项2：point
【互动反馈】
正确 Ben : Yes! It wants to talk with pictures!
错误 Ben : It is not pointing. What else?
【后置对话】Ben : That is the Speedy Monkey logo!"""),

    (138, """【任务标题】机器人又指了什么？
【资源配置】无
【情境引入】Robot draws a school mark on the blackboard.
【互动内容】It ___ at another mark.（音频）
选项1：points（正确）
选项2：talks
【互动反馈】
正确 Ben : Is that... a school?
错误 Ben : Look at what the robot is doing with the mark.
【后置对话】Ben : Is that a school?"""),

    # --- 互动 ---
    (150, """【任务标题】又是什么标记？
【资源配置】无
【情境引入】Robot draws a gift mark on the blackboard.
【互动内容】It points at another mark.
  KP：point — v. 指向
【互动反馈】
正确 → Ben : It is a gift!
错误 → Ben : Look at the mark. What is it?
【后置对话】Ben : Speedy Monkey? School? Gift?"""),

    (161, """【任务标题】你发现了什么？
【资源配置】无
【情境引入】Ben : Speedy Monkey? School? Gift?
【互动内容】Ben! I think I understand!
  KP：understand — v. 理解
【互动反馈】
正确 → Ben : What do you understand?
错误 → Ben : Look at the marks again.
【后置对话】User explains the spy theory"""),

    (168, """【任务标题】和 Ben 单独商量
【资源配置】无
【情境引入】User thinks the robot is a spy.
【互动内容】We need to talk! You and me!
  KP：talk — v. 说话
【互动反馈】
正确 → Ben : Okay! Let's figure this out.
错误 → Ben : We need to talk about what we found!
【后置对话】User : Vala School is a gift to Speedy Monkey!"""),

    (181, """【任务标题】快告诉镇长！
【资源配置】无
【情境引入】Ben : What should we do now?
【互动内容】We need to call Mayor Tom! Let's talk about it!
  KP：talk about... — 谈论...
【互动反馈】
正确 → Ben : Good idea. Let's call him now!
错误 → Ben : Who should we call for help?
【后置对话】Calling Mayor Tom..."""),

    (194, """【任务标题】指给镇长看
【资源配置】无
【情境引入】Tom : So you kids want to talk to me?
【互动内容】Look! I point at it.
  KP：point — v. 指向
【互动反馈】
正确 → Tom : The robot?
错误 → Tom : What are you pointing at?
【后置对话】Tom : Oh? A spy? In the classroom?"""),

    (207, """【任务标题】给镇长看证据
【资源配置】无
【情境引入】Tom : I don't understand. Anything else?
【互动内容】Look! Here are a lot of strange marks!
  KP：a lot of — det. 大量的
【互动反馈】
正确 → Tom : Hmm, I see.
错误 → Tom : Are there many strange marks?
【后置对话】User shows the blackboard to Tom"""),

    (224, """【任务标题】到底怎么回事？
【资源配置】无
【情境引入】Tom : The school isn't a gift to Speedy Monkey!
【互动内容】Wait. I don't understand.
  KP：I can/can't understand...
【互动反馈】
正确 → Lin : Why not let it tell you itself?
错误 → Lin : Let me help you understand.
【后置对话】Lin fixes the robot"""),

    # --- 核心互动-口语 ---
    (245, """【任务标题】向 Jay 和 Lin 道歉
【资源配置】无
【情境引入】Tom : Kids, do you have something to say?
【互动内容】
（口语表达）
I should talk to you.
I should understand you.
I can understand you now.
  KP：talk / understand
【互动反馈】
正确 → Jay : Thank you. We feel much better now.
错误 → Lin : Go on. Say what's in your heart.
【后置对话】Jay : I understand. Lin : We all make mistakes."""),
]

# Write
success = fail = 0
for row, text in configs:
    cell = f"{SID}!G{row}:G{row}"
    body = json.dumps({"valueRange": {"range": cell, "values": [[text]]}}, ensure_ascii=False)
    r = subprocess.run(['curl', '-s', '-X', 'PUT',
        f'https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{SST}/values',
        '-H', f'Authorization: Bearer {TOKEN}',
        '-H', 'Content-Type: application/json; charset=utf-8',
        '-d', body], capture_output=True, text=True, timeout=15)
    resp = json.loads(r.stdout)
    if resp.get('code') == 0:
        success += 1
        title = text.split('\n')[0].replace('【任务标题】', '')
        print(f'  ✅ Row {row:3d}  | {title}')
    else:
        fail += 1
        print(f'  ❌ Row {row:3d}  | {resp.get("msg","?")}')
        print(f'     debug: {r.stdout[:200]}')

print(f'\n写入结果：{success}成功 / {fail}失败')

if fail == 0:
    print('\n=== 回读验证 ===')
    for row, _ in configs:
        cell = f"{SID}!G{row}:G{row}"
        r = subprocess.run(['curl', '-s', '-X', 'GET',
            f'https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{SST}/values/{cell}?valueRenderOption=ToString',
            '-H', f'Authorization: Bearer {TOKEN}'], capture_output=True, text=True, timeout=15)
        resp = json.loads(r.stdout)
        vals = resp.get('data',{}).get('valueRange',{}).get('values',[[]])
        content = vals[0][0] if vals and vals[0] else None
        title = content.split('\n')[0].replace('【任务标题】', '') if content else 'EMPTY'
        status = '✅' if content else '❌ EMPTY'
        print(f'  {status} Row{row}: {title}')
else:
    print('\n⚠️ 有失败项，请检查')
