#!/usr/bin/env python3
"""Fix speaking_P2: 021601 expl+second, 021801 ability, 032601/032801 short expl"""
import requests, json, time

APP_TOKEN = "CMHSbUUjka3TrUsaxxEc297ongf"
APP_ID = "cli_a931175d41799cc7"
APP_SECRET = "Iw2vEfbjT6GtV0GhbxbZqfQ4nAPtbR14"
TABLE = "tblGoWYBmVI0IrvQ"

def get_token():
    r = requests.post("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
        json={"app_id": APP_ID, "app_secret": APP_SECRET}, timeout=10)
    return r.json()["tenant_access_token"]

token = get_token()

r = requests.get(f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE}/records?page_size=200",
    headers={"Authorization": f"Bearer {token}"}, timeout=15)

records = {}
for it in r.json()["data"]["items"]:
    qsid = it["fields"].get("题目集合 ID", "")
    if not qsid: continue
    jd_raw = it["fields"].get("jsonData", "")
    if not jd_raw: continue
    records[qsid] = {"rid": it["record_id"], "jd": json.loads(jd_raw)}

# ========== 021601: fill 4 explanations + empty second block ==========
fix_021601_expl = {
    0: "本题考察在特定情境下用英语回溯和描述的能力。回答时用过去时态，说明你最后一次看到玩具的地点。例如 'I last saw my toy near the big tree by the pond in the park.' 注意用 'last saw' 和准确的地点描述。",
    1: "本题考察用英语劝阻和提醒他人的能力。回答时用 'You should...' 或 'Don't...' 引导，加上原因说明。例如 'I would say, \"Don't climb too high — you might fall and hurt yourself!\"'",
    2: "本题考察用英语描述周边环境的能力。回答时用 'Near the park there is...' 列出附近地点。例如 'Near the park, there is a small shop, a library, and a playground.'",
    3: "本题考察用英语描述应对措施的能力。回答时说明你会怎么做以及找谁帮忙。例如 'If I lose something, I will first go back to where I last saw it, then ask a park worker for help.'",
}

rec = records["021601"]
qs = rec["jd"]["first"]["questionSet"]
for qi, expl in fix_021601_expl.items():
    qs[qi]["explanation"] = expl

rec["jd"]["second"] = {"type": "speaking_topic", "questionSetID": "021601", "questionSet": [], "ability": [], "explanation": ""}

new_jd = json.dumps(rec["jd"], ensure_ascii=False)
r = requests.put(
    f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE}/records/{rec['rid']}",
    headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
    json={"fields": {"jsonData": new_jd}}, timeout=15)
print(f"[021601] {'✅' if r.json().get('code')==0 else '❌'+r.json().get('msg','')}")
time.sleep(0.3)

# ========== 021801: fill 10 ability labels ==========
fix_021801_ab = {
    "first": {
        0: ["表达观点", "句型组织"],
        1: ["表达建议", "句型组织"],
        2: ["表达期望", "句型组织"],
        3: ["经历描述", "句型组织"],
        4: ["表达观点", "句型组织"],
    },
    "second": {
        0: ["表达观点", "句型组织"],
        1: ["表达建议", "句型组织"],
        2: ["表达期望", "句型组织"],
        3: ["经历描述", "句型组织"],
        4: ["表达观点", "句型组织"],
    }
}

rec = records["021801"]
for bn in ["first", "second"]:
    qs = rec["jd"].get(bn, {}).get("questionSet", [])
    for qi, ab in fix_021801_ab.get(bn, {}).items():
        if qi < len(qs):
            qs[qi]["ability"] = ab

new_jd = json.dumps(rec["jd"], ensure_ascii=False)
r = requests.put(
    f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE}/records/{rec['rid']}",
    headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
    json={"fields": {"jsonData": new_jd}}, timeout=15)
print(f"[021801] {'✅' if r.json().get('code')==0 else '❌'+r.json().get('msg','')}")
time.sleep(0.3)

# ========== 032601: extend 3 short explanations ==========
fix_032601_expl = {
    "first": {
        4: "本题考察用英语描述他人对你影响的能力。回答时说明谁、说过什么、以及你如何因此改变了对未来的想法。例如 'My teacher once told me that if you work hard for your dream, it will come true someday — that changed how I think about my future goals.'",
    },
    "second": {
        3: "本题考察用英语对比和阐述的能力。回答时说明远大梦想给你方向，小目标帮你一步步前进，两者缺一不可。例如 'Big dreams give us a direction, while small goals help us take steps every day. Both are important.'",
        4: "本题考察用英语给予鼓励和建议的能力。回答时用安慰加建议的结构。例如 'I would tell my friend not to give up, and share a story about someone who almost failed before they finally succeeded.'",
    }
}

rec = records["032601"]
for bn in ["first", "second"]:
    qs = rec["jd"].get(bn, {}).get("questionSet", [])
    for qi, expl in fix_032601_expl.get(bn, {}).items():
        if qi < len(qs):
            qs[qi]["explanation"] = expl

new_jd = json.dumps(rec["jd"], ensure_ascii=False)
r = requests.put(
    f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE}/records/{rec['rid']}",
    headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
    json={"fields": {"jsonData": new_jd}}, timeout=15)
print(f"[032601] {'✅' if r.json().get('code')==0 else '❌'+r.json().get('msg','')}")
time.sleep(0.3)

# ========== 032801: extend 6 short explanations ==========
fix_032801_expl = {
    "first": {
        1: "本题考察用英语描述无法自控行为的能力。回答时用过去时说明一种曾让你停不下来的活动，以及花了多长时间。例如 'I once started playing a new video game, and I just couldn't stop until I finished all the levels three days later.'",
        4: "本题考察用英语描述解决问题的策略。回答时说明你会分解问题、找人求助或暂停休息。例如 'When I find a problem too hard, I break it into smaller parts first, and if I still can't solve it, I ask my teacher for help.'",
    },
    "second": {
        0: "本题考察用英语描述并反思坏习惯的能力。回答时用 'I wish I could stop...' 并解释为什么这是坏习惯及你想如何改变。例如 'I wish I could stop checking my phone before bed because it makes it hard for me to fall asleep.'",
        2: "本题考察用英语描述长期学习投入的能力。回答时说明学了多久、进展如何、以及对结果的满意度。例如 'I've spent two years learning to play the piano. I'm proud of my progress, but I still have a lot to learn.'",
        3: "本题考察用英语描述压力感受和应对方式的能力。回答时说明你如何感知压力并如何缓解。例如 'When there is too much pressure, I feel tired and stressed. I usually take a short break, do some exercise, or talk to my parents about it.'",
        4: "本题考察用英语给予学弟学妹建议的能力。回答时用简单的建议句式，说明如何安排时间和寻求帮助。例如 'I would tell them to make a plan for their time, not wait until the last minute, and always ask for help when they need it.'",
    }
}

rec = records["032801"]
for bn in ["first", "second"]:
    qs = rec["jd"].get(bn, {}).get("questionSet", [])
    for qi, expl in fix_032801_expl.get(bn, {}).items():
        if qi < len(qs):
            qs[qi]["explanation"] = expl

new_jd = json.dumps(rec["jd"], ensure_ascii=False)
r = requests.put(
    f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE}/records/{rec['rid']}",
    headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
    json={"fields": {"jsonData": new_jd}}, timeout=15)
print(f"[032801] {'✅' if r.json().get('code')==0 else '❌'+r.json().get('msg','')}")

# ========== Write-back audit results ==========
print("\n=== 回填审核结果 ===")
audit_map = {
    "010199": "✅ 通过：first/second各6题，explanation/ability/answer完整",
    "021601": "✅ 已修复：4题explanation已填写，second块已补(空占位)",
    "021801": "✅ 已修复：first/second共10题ability已补全",
    "022001": "✅ 通过：first/second各5题，explanation完整",
    "022201": "✅ 通过：first/second各5题，含图片描述，explanation完整",
    "032601": "✅ 已修复：3题explanation延展为完整解析，含句型模板+示例回答",
    "032801": "✅ 已修复：6题explanation延展为完整解析，含句型模板+示例回答",
}

for qsid, result in audit_map.items():
    if qsid not in records: continue
    r = requests.put(
        f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE}/records/{records[qsid]['rid']}",
        headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
        json={"fields": {"审核结果": result}}, timeout=10)
    print(f"  {'✅' if r.json().get('code')==0 else '❌'} {qsid}")
    time.sleep(0.3)

print("\n全部完成")
