#!/usr/bin/env python3
"""Supplement abilityTag and complete ability/explanation for all 8 records."""
import subprocess, json

APP_TOKEN = "CMHSbUUjka3TrUsaxxEc297ongf"
TABLE_ID = "tblszuk1TeToofBF"
APP_ID = "cli_a931175d41799cc7"
APP_SECRET = "Iw2vEfbjT6GtV0GhbxbZqfQ4nAPtbR14"

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": APP_ID, "app_secret": APP_SECRET})
], capture_output=True, text=True)
TOKEN = json.loads(r.stdout)["tenant_access_token"]
print(f"Token: {TOKEN[:20]}...")

def get_jsonData(rid):
    url = f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE_ID}/records/{rid}"
    r = subprocess.run(["curl", "-s", "-X", "GET", url, "-H", f"Authorization: Bearer {TOKEN}"],
                       capture_output=True, text=True)
    return json.loads(r.stdout)['data']['record']['fields']

def update_jsonData(rid, jd):
    url = f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE_ID}/records/{rid}"
    body = json.dumps({"fields": {"jsonData": json.dumps(jd, ensure_ascii=False)}}, ensure_ascii=False)
    r = subprocess.run(["curl", "-s", "-X", "PUT", url,
                        "-H", f"Authorization: Bearer {TOKEN}",
                        "-H", "Content-Type: application/json",
                        "-d", body], capture_output=True, text=True)
    return json.loads(r.stdout)

# Per-record ability / abilityTag / explanation definitions
SPECS = {
    "recvjzbkvoOgvy": {  # 022201
        "ability": ["短消息写作｜邮件/便条", "衔接与连贯｜指代与连词使用", "句型组织｜邮件段落排序"],
        "abilityTag": ["短消息写作", "衔接与连贯", "句型组织"],
        "explanation": '正确的邮件结构：称呼（Dear Max,）→ 正文第一句（告诉Max你听说了旧盒子："I heard you found..."）→ 正文第二句（询问盒子里有什么："What did you find..."）→ 正文第三句（建议一起打开："Let\'s open it..."）→ 结尾敬语（Take care,）→ 署名（Alex）。学生需通过指代词（it指代the old box）和时间提示（after school）判断句子间的逻辑顺序。',
    },
    "recvjzblhhNt7Q": {  # 022301
        "ability": ["短消息写作｜邮件/便条", "衔接与连贯｜指代与连词使用", "句型组织｜邮件段落排序"],
        "abilityTag": ["短消息写作", "衔接与连贯", "句型组织"],
        "explanation": "正确的邮件结构：称呼（Dear Emma,）→ 正文第一句（描述今天做了什么：\"We worked hard...\"）→ 正文第二句（描述花园现状：\"All the new flowers...\"）→ 正文第三句（建议下次行动：\"Next time we should...\"）→ 结尾（Your friend,）→ 署名（Lily）。学生需通过时间词（this afternoon / next time）判断事件先后顺序，通过\"And\"连词识别并列描述关系。",
    },
    "recvjzblXOJ7Fs": {  # 022401
        "ability": ["短消息写作｜邮件/便条", "衔接与连贯｜指代与连词使用", "句型组织｜邮件段落排序"],
        "abilityTag": ["短消息写作", "衔接与连贯", "句型组织"],
        "explanation": '正确的邮件结构：称呼（Dear Sophie,）→ 正文第一句（告知探病事实："Tom and I went..."）→ 正文第二句（描述Jack当前状态："He is feeling much better..."）→ 正文第三句（建议对方可做的事："You could send him..."）→ 结尾敬语（Warmly,）→ 署名（Lily）。学生需通过人称指代（him指代Jack）和连词（and he smiled when...）判断句子衔接关系。',
    },
    "recvjzXjMKAQ4i": {  # 032501
        "ability": ["短消息写作｜邮件/便条", "衔接与连贯｜指代与连词使用", "情感表达｜鼓励与共情", "句型组织｜邮件段落排序"],
        "abilityTag": ["短消息写作", "衔接与连贯", "情感表达", "句型组织"],
        "explanation": '正确的邮件结构：称呼（Dear Ben,）→ 正文第一句（表达听说了对方的担忧："I heard you are worried..."）→ 正文第二句（共情自己的紧张感："I feel nervous...but practising helps..."）→ 正文第三句（鼓励不要放弃："Please don\'t give up..."）→ 结尾敬语（Yours truly,）→ 署名（Sam）。学生需通过转折连词（but）和破折号（—解释说明"you have already worked so hard"）判断句子逻辑关系。',
    },
    "recvjzXklYIE05": {  # 032601
        "ability": ["短消息写作｜邮件/便条", "衔接与连贯｜指代与连词使用", "社交写作｜感谢信", "句型组织｜邮件段落排序"],
        "abilityTag": ["短消息写作", "衔接与连贯", "社交写作", "句型组织"],
        "explanation": '正确的邮件结构：称呼（Dear Mr. Brown,）→ 正文第一句（表达感谢："Thank you so much..."）→ 正文第二句（描述最喜欢的内容："I enjoyed the planet show..."）→ 正文第三句（请求分享照片："Could you please share..."）→ 结尾敬语（Warm regards,）→ 署名（Lucy）。学生需通过破折号（—补充说明"really amazing"）和指代词（the trip回指上文博物馆之旅）判断句子衔接顺序。',
    },
    "recvjzXkYnsQ8r": {  # 032701
        "ability": ["短消息写作｜邮件/便条", "衔接与连贯｜指代与连词使用", "描述性写作｜地点与人物", "句型组织｜邮件段落排序"],
        "abilityTag": ["短消息写作", "衔接与连贯", "描述性写作", "句型组织"],
        "explanation": '正确的邮件结构：称呼（Dear Anna,）→ 正文第一句（描述去过咖啡馆："I visited a lovely little cafe..."）→ 正文第二句（描述店员特点："The people working there..."）→ 正文第三句（建议一起去："We should go there together..."）→ 结尾敬语（Kind regards,）→ 署名（Emma）。学生需通过指代词（there指代the cafe）和破折号（—补充解释"you would love it"）判断句子间的逻辑顺序。',
    },
    "recvjzXlxz4r3i": {  # 032801
        "ability": ["短消息写作｜邮件/便条", "衔接与连贯｜指代与连词使用", "问题解决｜求助与建议", "句型组织｜邮件段落排序"],
        "abilityTag": ["短消息写作", "衔接与连贯", "问题解决", "句型组织"],
        "explanation": '正确的邮件结构：称呼（Dear Miss Green,）→ 正文第一句（说明项目停止工作："Our science project has suddenly stopped..."）→ 正文第二句（描述已尝试的方案："We have tried changing the batteries, but..."）→ 正文第三句（请求建议："Could you give us some advice..."）→ 结尾敬语（Gratefully,）→ 署名（Tom）。学生需通过转折连词（but）和因果指代（"that did not fix..."中that指代changing batteries）判断句子逻辑。',
    },
    "recvjzXm5yEXBY": {  # 032901
        "ability": ["短消息写作｜邮件/便条", "衔接与连贯｜指代与连词使用", "描述性写作｜场景与情绪", "句型组织｜邮件段落排序"],
        "abilityTag": ["短消息写作", "衔接与连贯", "描述性写作", "句型组织"],
        "explanation": '正确的邮件结构：称呼（Dear Sophie,）→ 正文第一句（描述正在派对："I\'m at my mum\'s birthday party..."）→ 正文第二句（描述家人表现："My little sister is dancing...Dad seems..."）→ 正文第三句（表达感受："I feel so lucky..."）→ 结尾敬语（With love,）→ 署名（Jessica）。学生需通过并列连词（and）和时间提示词（right now / tonight）判断描述的层次推进。',
    },
}

for rid, spec in SPECS.items():
    fields = get_jsonData(rid)
    jd = json.loads(fields["jsonData"])
    qid = jd["first"]["questionSetID"]

    jd["first"]["ability"] = spec["ability"]
    jd["first"]["abilityTag"] = spec["abilityTag"]
    jd["first"]["explanation"] = spec["explanation"]

    print(f"[{qid}] updating...", end=" ")
    resp = update_jsonData(rid, jd)
    if resp.get("code") == 0:
        print("✅")
    else:
        print(f"❌ {resp.get('msg')}")

print("\nDone.")
