#!/usr/bin/env python3
"""Update 8 writing P1 email records in bitable."""
import subprocess, json, sys

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

# Get token
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 obtained: {TOKEN[:20]}...")

def update_record(record_id, fields):
    """Update a single record via curl."""
    url = f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE_ID}/records/{record_id}"
    body = json.dumps({"fields": fields}, 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)
    resp = json.loads(r.stdout)
    if resp.get("code") != 0:
        print(f"  ❌ FAILED: {resp.get('msg', resp)}")
        return False
    print(f"  ✅ OK")
    return True

# ========== Record definitions ==========

records = {
    # ---- L2 B级 ----
    "recvjzbkvoOgvy": {  # 022201
        "jsonData": json.dumps({
            "first": {
                "category": "writing",
                "type": "writing_email",
                "questionSetID": "022201",
                "textDesc": "Your friend Max found an old box in the attic and you are curious about it. Write an email to Max.\n\nIn your email:\n1. tell Max you heard about the old box\n2. ask what he found inside the box\n3. suggest opening the box together",
                "optionSetList": [
                    "Dear Max,",
                    "Take care,",
                    "I heard you found an old box in the attic.",
                    "What did you find inside it?",
                    "Alex",
                    "Let's open it together after school."
                ],
                "answerSet": [0, 2, 3, 5, 1, 4],
                "ability": ["短消息写作｜邮件/便条", "衔接与连贯｜连词使用"],
                "explanation": "6句邮件排序：Dear开头→描述听说的消息→询问盒子内容→建议一起打开→Take care收尾→Alex署名。",
                "questionSet": []
            },
            "second": {}
        }, ensure_ascii=False),
        "题目1": "【题目描述】\nYour friend Max found an old box in the attic and you are curious about it. Write an email to Max.\n\nIn your email:\n1. tell Max you heard about the old box\n2. ask what he found inside the box\n3. suggest opening the box together\n\n【段落列表】\nA. Dear Max,\nB. Take care,\nC. I heard you found an old box in the attic.\nD. What did you find inside it?\nE. Alex\nF. Let's open it together after school.",
        "审校结果": "✅ OK | 2026-05-22 小研优化"
    },

    "recvjzblhhNt7Q": {  # 022301
        "jsonData": json.dumps({
            "first": {
                "category": "writing",
                "type": "writing_email",
                "questionSetID": "022301",
                "textDesc": "You and your friend Emma are working on a community garden. You spent the afternoon there. Write an email to Emma.\n\nIn your email:\n1. tell Emma what you did in the garden today\n2. describe what the garden looks like now\n3. suggest what to do next time",
                "optionSetList": [
                    "Your friend,",
                    "Dear Emma,",
                    "Next time we should water the young trees together.",
                    "Lily",
                    "We worked hard in the community garden this afternoon.",
                    "All the new flowers make the garden look really colourful now."
                ],
                "answerSet": [1, 4, 5, 2, 0, 3],
                "ability": ["短消息写作｜邮件/便条", "衔接与连贯｜连词使用"],
                "explanation": "6句邮件排序：Dear开头→描述今天劳动内容→描述花园现状→建议下次行动→Your friend收尾→Lily署名。",
                "questionSet": []
            },
            "second": {}
        }, ensure_ascii=False),
        "题目1": "【题目描述】\nYou and your friend Emma are working on a community garden. You spent the afternoon there. Write an email to Emma.\n\nIn your email:\n1. tell Emma what you did in the garden today\n2. describe what the garden looks like now\n3. suggest what to do next time\n\n【段落列表】\nA. Your friend,\nB. Dear Emma,\nC. Next time we should water the young trees together.\nD. Lily\nE. We worked hard in the community garden this afternoon.\nF. All the new flowers make the garden look really colourful now.",
        "审校结果": "✅ OK | 2026-05-22 小研优化"
    },

    "recvjzblXOJ7Fs": {  # 022401
        "jsonData": json.dumps({
            "first": {
                "category": "writing",
                "type": "writing_email",
                "questionSetID": "022401",
                "textDesc": "Your friend Jack is in hospital. You visited him today with your friend Tom. Write an email to Sophie.\n\nIn your email:\n1. tell Sophie you visited Jack at the hospital\n2. describe how Jack is feeling now\n3. suggest what Sophie can do to help",
                "optionSetList": [
                    "Warmly,",
                    "Tom and I went to the hospital to visit Jack today.",
                    "Dear Sophie,",
                    "You could send him a card to cheer him up.",
                    "Lily",
                    "He is feeling much better and he smiled when he saw us."
                ],
                "answerSet": [2, 1, 5, 3, 0, 4],
                "ability": ["短消息写作｜邮件/便条", "衔接与连贯｜连词使用"],
                "explanation": "6句邮件排序：Dear开头→告知探病事实→描述Jack状态→建议对方行动→Warmly收尾→Lily署名。",
                "questionSet": []
            },
            "second": {}
        }, ensure_ascii=False),
        "题目1": "【题目描述】\nYour friend Jack is in hospital. You visited him today with your friend Tom. Write an email to Sophie.\n\nIn your email:\n1. tell Sophie you visited Jack at the hospital\n2. describe how Jack is feeling now\n3. suggest what Sophie can do to help\n\n【段落列表】\nA. Warmly,\nB. Tom and I went to the hospital to visit Jack today.\nC. Dear Sophie,\nD. You could send him a card to cheer him up.\nE. Lily\nF. He is feeling much better and he smiled when he saw us.",
        "审校结果": "✅ OK | 2026-05-22 小研优化"
    },

    # ---- L2 C级 ----
    "recvjzXjMKAQ4i": {  # 032501
        "jsonData": json.dumps({
            "first": {
                "category": "writing",
                "type": "writing_email",
                "questionSetID": "032501",
                "textDesc": "Your friend Ben is worried about the school concert and wants to give up. Write an email to encourage him.\n\nIn your email:\n1. tell Ben you heard he is worried about the concert\n2. share how you feel about performing too\n3. encourage him not to give up",
                "optionSetList": [
                    "Yours truly,",
                    "I feel nervous before performing too, but practising helps me feel ready.",
                    "Dear Ben,",
                    "Please don't give up — you have already worked so hard for this.",
                    "Sam",
                    "I heard you are worried about the school concert."
                ],
                "answerSet": [2, 5, 1, 3, 0, 4],
                "ability": ["短消息写作｜邮件/便条", "衔接与连贯｜连词使用", "情感表达｜鼓励与共情"],
                "explanation": "6句邮件排序：Dear开头→表达听说了对方的担忧→共情自己也有紧张→鼓励不要放弃→Yours truly收尾→Sam署名。",
                "questionSet": []
            },
            "second": {}
        }, ensure_ascii=False),
        "题目1": "【题目描述】\nYour friend Ben is worried about the school concert and wants to give up. Write an email to encourage him.\n\nIn your email:\n1. tell Ben you heard he is worried about the concert\n2. share how you feel about performing too\n3. encourage him not to give up\n\n【段落列表】\nA. Yours truly,\nB. I feel nervous before performing too, but practising helps me feel ready.\nC. Dear Ben,\nD. Please don't give up — you have already worked so hard for this.\nE. Sam\nF. I heard you are worried about the school concert.",
        "审校结果": "✅ OK | 2026-05-22 小研优化"
    },

    "recvjzXklYIE05": {  # 032601
        "jsonData": json.dumps({
            "first": {
                "category": "writing",
                "type": "writing_email",
                "questionSetID": "032601",
                "textDesc": "You just came back from a wonderful school trip to the science museum, organised by your teacher Mr. Brown. Write a thank-you email to him.\n\nIn your email:\n1. thank Mr. Brown for organising the school trip\n2. tell him what you enjoyed most at the museum\n3. ask him to share the photos he took",
                "optionSetList": [
                    "Warm regards,",
                    "I enjoyed the planet show the most — it was really amazing.",
                    "Dear Mr. Brown,",
                    "Could you please share the photos you took during the trip?",
                    "Thank you so much for the wonderful trip to the science museum.",
                    "Lucy"
                ],
                "answerSet": [2, 4, 1, 3, 0, 5],
                "ability": ["短消息写作｜邮件/便条", "衔接与连贯｜连词使用", "社交写作｜感谢信"],
                "explanation": "6句邮件排序：Dear开头→表达感谢→描述最喜欢的展览→请求分享照片→Warm regards收尾→Lucy署名。",
                "questionSet": []
            },
            "second": {}
        }, ensure_ascii=False),
        "题目1": "【题目描述】\nYou just came back from a wonderful school trip to the science museum, organised by your teacher Mr. Brown. Write a thank-you email to him.\n\nIn your email:\n1. thank Mr. Brown for organising the school trip\n2. tell him what you enjoyed most at the museum\n3. ask him to share the photos he took\n\n【段落列表】\nA. Warm regards,\nB. I enjoyed the planet show the most — it was really amazing.\nC. Dear Mr. Brown,\nD. Could you please share the photos you took during the trip?\nE. Thank you so much for the wonderful trip to the science museum.\nF. Lucy",
        "审校结果": "✅ OK | 2026-05-22 小研优化"
    },

    "recvjzXkYnsQ8r": {  # 032701
        "jsonData": json.dumps({
            "first": {
                "category": "writing",
                "type": "writing_email",
                "questionSetID": "032701",
                "textDesc": "You visited a lovely little cafe that your cousin found last week. Write an email to your friend Anna to tell her about it.\n\nIn your email:\n1. tell Anna about the cafe you visited\n2. describe the people you met there\n3. suggest visiting the cafe together sometime",
                "optionSetList": [
                    "Kind regards,",
                    "I visited a lovely little cafe that my cousin found last week.",
                    "We should go there together one afternoon — you would really love it.",
                    "The people working there were so friendly and kind to every customer.",
                    "Emma",
                    "Dear Anna,"
                ],
                "answerSet": [5, 1, 3, 2, 0, 4],
                "ability": ["短消息写作｜邮件/便条", "衔接与连贯｜连词使用", "描述性写作｜地点与人物"],
                "explanation": "6句邮件排序：Dear开头→描述去过咖啡馆→描述店员友好→建议一起去→Kind regards收尾→Emma署名。",
                "questionSet": []
            },
            "second": {}
        }, ensure_ascii=False),
        "题目1": "【题目描述】\nYou visited a lovely little cafe that your cousin found last week. Write an email to your friend Anna to tell her about it.\n\nIn your email:\n1. tell Anna about the cafe you visited\n2. describe the people you met there\n3. suggest visiting the cafe together sometime\n\n【段落列表】\nA. Kind regards,\nB. I visited a lovely little cafe that my cousin found last week.\nC. We should go there together one afternoon — you would really love it.\nD. The people working there were so friendly and kind to every customer.\nE. Emma\nF. Dear Anna,",
        "审校结果": "✅ OK | 2026-05-22 小研优化"
    },

    "recvjzXlxz4r3i": {  # 032801
        "jsonData": json.dumps({
            "first": {
                "category": "writing",
                "type": "writing_email",
                "questionSetID": "032801",
                "textDesc": "Your group's science project has suddenly stopped working and you need your teacher's help. Write an email to Miss Green.\n\nIn your email:\n1. tell Miss Green your science project has stopped working\n2. describe what you have tried to fix it\n3. ask for her advice on what to do next",
                "optionSetList": [
                    "Our science project has suddenly stopped working and we are not sure why.",
                    "Gratefully,",
                    "Could you give us some advice on what we should try next?",
                    "Tom",
                    "We have tried changing the batteries, but that did not fix the problem.",
                    "Dear Miss Green,"
                ],
                "answerSet": [5, 0, 4, 2, 1, 3],
                "ability": ["短消息写作｜邮件/便条", "衔接与连贯｜连词使用", "问题解决｜求助与建议"],
                "explanation": "6句邮件排序：Dear开头→说明项目故障→描述已尝试方案→请求建议→Gratefully收尾→Tom署名。",
                "questionSet": []
            },
            "second": {}
        }, ensure_ascii=False),
        "题目1": "【题目描述】\nYour group's science project has suddenly stopped working and you need your teacher's help. Write an email to Miss Green.\n\nIn your email:\n1. tell Miss Green your science project has stopped working\n2. describe what you have tried to fix it\n3. ask for her advice on what to do next\n\n【段落列表】\nA. Our science project has suddenly stopped working and we are not sure why.\nB. Gratefully,\nC. Could you give us some advice on what we should try next?\nD. Tom\nE. We have tried changing the batteries, but that did not fix the problem.\nF. Dear Miss Green,",
        "审校结果": "✅ OK | 2026-05-22 小研优化"
    },

    "recvjzXm5yEXBY": {  # 032901
        "jsonData": json.dumps({
            "first": {
                "category": "writing",
                "type": "writing_email",
                "questionSetID": "032901",
                "textDesc": "You are at your mum's birthday party and having a wonderful time. Write an email to your friend Sophie to share the happy news.\n\nIn your email:\n1. tell Sophie about your mum's birthday party\n2. describe what everyone is doing at the party\n3. share how you feel about this special day",
                "optionSetList": [
                    "With love,",
                    "My little sister is dancing happily and Dad seems in a wonderful mood tonight.",
                    "I'm at my mum's birthday party right now and everyone is having a great time.",
                    "I feel so lucky to celebrate this special day with my whole family.",
                    "Dear Sophie,",
                    "Jessica"
                ],
                "answerSet": [4, 2, 1, 3, 0, 5],
                "ability": ["短消息写作｜邮件/便条", "衔接与连贯｜连词使用", "描述性写作｜场景与情绪"],
                "explanation": "6句邮件排序：Dear开头→描述正在派对→描述大家在做的事→表达感受→With love收尾→Jessica署名。",
                "questionSet": []
            },
            "second": {}
        }, ensure_ascii=False),
        "题目1": "【题目描述】\nYou are at your mum's birthday party and having a wonderful time. Write an email to your friend Sophie to share the happy news.\n\nIn your email:\n1. tell Sophie about your mum's birthday party\n2. describe what everyone is doing at the party\n3. share how you feel about this special day\n\n【段落列表】\nA. With love,\nB. My little sister is dancing happily and Dad seems in a wonderful mood tonight.\nC. I'm at my mum's birthday party right now and everyone is having a great time.\nD. I feel so lucky to celebrate this special day with my whole family.\nE. Dear Sophie,\nF. Jessica",
        "审校结果": "✅ OK | 2026-05-22 小研优化"
    },
}

# ========== Execute updates ==========
print(f"\nUpdating {len(records)} records...\n")
success = 0
fail = 0

for rid, fields in records.items():
    qid = json.loads(fields["jsonData"])["first"]["questionSetID"]
    print(f"[{qid}] {rid} ...", end=" ")
    if update_record(rid, fields):
        success += 1
    else:
        fail += 1

print(f"\nDone: {success} OK, {fail} failed")
