#!/usr/bin/env python3
"""Fix 021801 题组2 - replace duplicate questions with new ones based on new images."""
import subprocess, json

APP_TOKEN = "CMHSbUUjka3TrUsaxxEc297ongf"
TABLE_ID = "tblGoWYBmVI0IrvQ"
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, timeout=10)
TOKEN = json.loads(r.stdout)["tenant_access_token"]

rid = "recvjz5Hs8gpCJ"
url = f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE_ID}/records/{rid}"

# GET current
r = subprocess.run(["curl", "-s", "-X", "GET", url, "-H", f"Authorization: Bearer {TOKEN}"],
    capture_output=True, text=True, timeout=10)
fields = json.loads(r.stdout)['data']['record']['fields']
jd = json.loads(fields['jsonData'])

# ===== Update 题组2 (second) =====
jd['second']['textDesc'] = "Now look at these pictures again. They show more ways children help and encourage each other. Talk about what you see and share your own experiences."
jd['second']['imageDesc'] = "Four new images about helping and caring for each other: 1st: A child brings homework to help a quiet classmate — desk is open with books and pencils. 2nd: In the school corridor, a child kneels to tie another classmate's shoelaces; the classmate looks up gratefully. 3rd: Two children plant a young tree in the garden — one holds the sapling, the other adds soil, both looking hopeful. 4th: At a school assembly, a child stands on stage and receives an award for helping others; classmates stand up and applaud."

jd['second']['questionSet'] = [
    {
        "content": "What do you do when a classmate looks shy or alone at school?",
        "ability": ["表达观点", "句型组织"],
        "explanation": "可以分享主动接近新同学的经历，例如 \"I would go and say hello with a smile. I can ask him to sit with us at lunch so he doesn't feel lonely.\" 也可以说 \"I invite her to play with my friends and show her around the school.\""
    },
    {
        "content": "Do you think small acts of kindness, like tying shoelaces, are as important as big help? Why?",
        "ability": ["表达观点", "句型组织"],
        "explanation": "可以从日常小事角度回答，例如 \"Yes, because small things can make someone's day. When you tie someone's shoelaces, they know you care about them.\" 也可以对比回答：\"Small help is just as important because everyone needs a hand sometimes, even for little things.\""
    },
    {
        "content": "Tell us about a time when you and a friend worked together on something. How did it go?",
        "ability": ["经历描述", "句型组织"],
        "explanation": "用过去式描述合作经历，例如 \"Last spring my friend and I planted flowers in the school garden. She dug the holes and I put the seeds in. We felt proud when the flowers bloomed.\" 也可以说 \"We cleaned the classroom together after school and finished much faster than doing it alone.\""
    },
    {
        "content": "How do you feel when someone thanks you or gives you praise for helping?",
        "ability": ["表达观点", "句型组织"],
        "explanation": "可以表达被认可的温暖感，例如 \"It makes me feel warm and happy. I feel like what I did really mattered to someone.\" 也可以说 \"I feel proud but also a little shy. It encourages me to help more people in the future.\""
    },
    {
        "content": "What kind of person do you want to be — someone who helps others every day? Why?",
        "ability": ["表达观点", "句型组织"],
        "explanation": "可以展望自己的品格成长，例如 \"I want to be the kind of person who helps others without thinking twice. Helping makes the world a kinder place and I want to be part of that.\" 也可以说 \"Yes, because when I help someone and see them smile, it makes my day better too.\""
    }
]

# ===== Update 题目2 display text =====
题目2_lines = [
    "【题目描述】",
    jd['second']['textDesc'],
    "",
    "【热词】",
    "sick,classmate,help,homework,encourage,goal,dream,support,friend,teamwork",
    "",
    "【图片描述】",
    jd['second']['imageDesc'],
    "",
    "【题目】",
]
for i, q in enumerate(jd['second']['questionSet'], 1):
    exp = q['explanation'].replace('\n', ' ')
    题目2_lines.append(f"{i}. {q['content']}")
    题目2_lines.append(f"- 解析：{exp}")
    题目2_lines.append("")

fields_update = {
    "jsonData": json.dumps(jd, ensure_ascii=False),
    "题目2": "\n".join(题目2_lines),
    "审核结果": "✅ OK | 2026-05-22 小研优化题组2",
}

body = json.dumps({"fields": fields_update}, 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, timeout=10)
resp = json.loads(r.stdout)
if resp.get("code") == 0:
    print("✅ 021801 题组2 已更新")

    # Verify
    r = subprocess.run(["curl", "-s", "-X", "GET", url, "-H", f"Authorization: Bearer {TOKEN}"],
        capture_output=True, text=True, timeout=10)
    jd2 = json.loads(json.loads(r.stdout)['data']['record']['fields']['jsonData'])
    qs1 = jd2['first']['questionSet']
    qs2 = jd2['second']['questionSet']
    
    print("\n题组1 vs 题组2 问题对比:")
    for i in range(5):
        same = "🟡 相同" if qs1[i]['content'] == qs2[i]['content'] else "🟢 不同"
        print(f"  Q{i+1}: {same}")
        print(f"    题1: {qs1[i]['content']}")
        print(f"    题2: {qs2[i]['content']}")
else:
    print(f"❌ {resp}")
