#!/usr/bin/env python3
"""
P4 短对话选择题批量改写脚本
将 3 人对话改为 2 人对话，重写题目
"""
import json, subprocess, os, sys, time

APP_TOKEN = "CMHSbUUjka3TrUsaxxEc297ongf"
TABLE_ID = "tblVmeDtBDKsAEfz"
BASE_DIR = os.path.expanduser("~/.openclaw/workspace-xiaoyan")
OPERATE_SCRIPT = os.path.join(BASE_DIR, "business_production/_shared/lark_bitable_operate_as_bot/scripts/operate_bitable.sh")

def run_operate(action, *args):
    """Run the operate_bitable.sh script"""
    cmd = ["bash", OPERATE_SCRIPT, action, APP_TOKEN, TABLE_ID] + list(args)
    result = subprocess.run(cmd, capture_output=True, text=True)
    return json.loads(result.stdout)

def get_records():
    """Get all records"""
    result = run_operate("list_records", "50")
    return result.get("data", {}).get("items", [])

def update_record(record_id, fields_json_str):
    """Update a record"""
    result = run_operate("update_record", record_id, fields_json_str)
    return result

def safe_json(s):
    """Safely dump JSON"""
    return json.dumps(s, ensure_ascii=False)

def make_qs(question_desc, audio_file, question_text, options, answer_idx, ability_list, explanation_cn):
    """Create a question set item"""
    return {
        "questionDesc": question_desc,
        "questionAudio": audio_file,
        "question": question_text,
        "options": options,
        "answer": [answer_idx],
        "ability": ability_list,
        "explanation": explanation_cn
    }

def make_block(qsid, questions):
    """Create a first/second block"""
    return {
        "category": "listening",
        "type": "listening_choiceShort",
        "questionSetID": qsid,
        "questionSet": questions
    }

def make_q1_text(questions):
    """Generate 题目1 text from question list"""
    lines = []
    for i, q in enumerate(questions, 1):
        lines.append(f"{i}.")
        lines.append(f"【描述】{q['questionDesc']}")
        lines.append(f"【听力文本】")
        if 'dialogue' in q:
            lines.append(q['dialogue'])
        lines.append(f"【题目】")
        lines.append(q['question'])
        for j, opt in enumerate(q['options']):
            marker = "（正确）" if j == q['answer'][0] else ""
            lines.append(f"{chr(65+j)}. {opt}{marker}")
        lines.append("")
    return "\n".join(lines)

# ============================================================
# 021301 - 邻居话题 (neighbour/beard/actor/brave)
# first: 5 Qs | second: 5 Qs
# ============================================================
QSID_021301_FIRST = [
    make_qs(
        "You will hear two people talking about their neighbours.",
        "021301-00.mp3",
        "Whose neighbour has a real beard?",
        ["Ben's neighbour", "Lucy's neighbour", "Daisy's neighbour"],
        0,
        ["显性事实理解｜关键词识别"],
        "Ben说'My neighbour has a long, real beard'，明确提到他的邻居有真胡子，Daisy未出现在对话中，是干扰项。"
    ),
    make_qs(
        "You will hear two people describing someone they know.",
        "021301-01.mp3",
        "What does Ben say about the actor?",
        ["He has a fake beard", "He looks different at home", "He does his own stunts"],
        2,
        ["听力细节理解"],
        "Ben说'He does his own stunts. He is a real professional.'，说明这位演员自己做特技动作。选项C为正确答案。"
    ),
    make_qs(
        "You will hear two people talking about someone in their area.",
        "021301-02.mp3",
        "Whose neighbour has a beard that changes how he looks?",
        ["Lucy's neighbour", "Johnny's neighbour", "Daisy's neighbour"],
        1,
        ["显性事实理解｜关键词识别"],
        "Johnny说'My neighbour has a long, real beard. It makes him look quite different.'，胡子改变了他的样子。Daisy不在对话中，是干扰项。"
    ),
    make_qs(
        "You will hear two people sharing stories.",
        "021301-03.mp3",
        "What does Lucy say about her neighbour?",
        ["He is kind and helpful", "He looks different at home", "He was brave like a hero"],
        2,
        ["听力细节理解"],
        "Lucy说'My neighbour did something brave last week. He was like a hero.'，她的邻居做了勇敢的事。选项C为正确答案。"
    ),
    make_qs(
        "You will hear two people giving their opinions.",
        "021301-04.mp3",
        "What does Lucy think about beards for actors?",
        ["A real beard looks more authentic", "A fake beard is better on stage", "Beards are not important for actors"],
        0,
        ["听力细节理解"],
        "Lucy说'I think a real beard suits an actor if the role needs it. It looks more authentic.'，她认为真胡子让演员看起来更真实。"
    ),
]

# Dialogues for 021301 first
QSID_021301_FIRST_DIALOGUES = [
    """Ben: Hi, Lucy. My neighbour is an actor. He has a long, real beard.
Lucy: That's interesting, Ben. My neighbour is very brave. He once helped a child in our street.""",
    """Ben: I know a brave actor. He does his own stunts. He is a real professional.
Lucy: Wow, Ben. My neighbour is an actor too. But he looks very different at home, without his costume.""",
    """Johnny: There's a new neighbour on our street. He's an actor and seems very brave.
Lucy: My neighbour has a long, real beard. It makes him look quite different, Johnny.""",
    """Lucy: My neighbour did something brave last week. He was like a hero.
Johnny: That's amazing, Lucy. The actor in that play had a fake beard, but my neighbour's beard is real.""",
    """Lucy: I think a real beard suits an actor if the role needs it. It looks more authentic.
Johnny: That's a good point, Lucy. A brave person and a good neighbour can be very different things.""",
]

for i, d in enumerate(QSID_021301_FIRST_DIALOGUES):
    QSID_021301_FIRST[i]["dialogue"] = d

QSID_021301_FIRST_BLOCK = make_block("021301", QSID_021301_FIRST)

QSID_021301_SECOND = [
    make_qs(
        "You will hear two people talking about what they did yesterday.",
        "021301-05.mp3",
        "What did Ben do yesterday?",
        ["Tidied his room", "Looked for his keys", "Fixed a bike"],
        0,
        ["显性事实理解｜关键词识别"],
        "Ben说'I needed to tidy my room. It took a long time.'，他昨天整理了房间。"
    ),
    make_qs(
        "You will hear two people talking about their weekend plans.",
        "021301-06.mp3",
        "Whose plan is to go to the library?",
        ["Otis's plan", "Daisy's plan", "Ben's plan"],
        1,
        ["显性事实理解｜关键词识别"],
        "Daisy说'I want to find a new book to read. I'll go to the library.'，她的计划是去图书馆找书。Otis提到了等cousin，但Daisy提到了library。"
    ),
    make_qs(
        "You will hear two people talking about a problem they had.",
        "021301-07.mp3",
        "What does Johnny say was his problem?",
        ["He didn't have the right instruction", "He lost his phone", "He waited a long time for a bus"],
        0,
        ["听力细节理解"],
        "Johnny说'I tried to cut some paper, but I didn't have the right instruction. It was messy.'，他没有正确的操作说明。"
    ),
    make_qs(
        "You will hear two people talking about what they are doing now.",
        "021301-08.mp3",
        "What is Lucy doing at the moment?",
        ["Fixing a shelf", "Helping her brother look for glasses", "Tidying papers"],
        1,
        ["听力细节理解"],
        "Lucy说'I'm helping my brother look for his glasses. They are missing.'，她正在帮弟弟找眼镜。"
    ),
    make_qs(
        "You will hear two people giving advice.",
        "021301-09.mp3",
        "What advice does Lucy give?",
        ["Always read the instruction first", "Book the hotel early online", "Ask someone for help if you're lost"],
        2,
        ["听力细节理解"],
        "Lucy说'If you can't find your way, don't wait. Ask someone for help.'，她建议迷路时主动问路。"
    ),
]

QSID_021301_SECOND_DIALOGUES = [
    """Ben: Hi, Lucy. Yesterday I needed to tidy my room. It took a long time.
Lucy: Oh, Ben. I had to look for my keys. I couldn't find them anywhere for a while.""",
    """Daisy: My plan is to wait for my cousin to arrive. He's coming by train.
Ben: That sounds nice, Daisy. I want to find a new book to read. I'll go to the library.""",
    """Johnny: I tried to cut some paper, but I didn't have the right instruction. It was messy.
Lucy: That's too bad, Johnny. I was looking for my phone to call for help, but I couldn't find it.""",
    """Lucy: I'm helping my brother look for his glasses. They are missing.
Ben: Good luck, Lucy. I'm trying to fix this shelf. I hope I can do it.""",
    """Lucy: If you can't find your way, don't wait. Ask someone for help.
Johnny: That's good advice, Lucy. When you plan a trip, remember to look for the hotel online early.""",
]

for i, d in enumerate(QSID_021301_SECOND_DIALOGUES):
    QSID_021301_SECOND[i]["dialogue"] = d

QSID_021301_SECOND_BLOCK = make_block("021301", QSID_021301_SECOND)

# ============================================================
# 021401 - 日常话题 (newspaper/plan/backpack/repair/seat)
# first: 5 Qs | second: 5 Qs
# ============================================================
QSID_021401_FIRST = [
    make_qs(
        "You will hear two people talking about their morning routine.",
        "021401-00.mp3",
        "What does Ben talk about doing in the morning?",
        ["Reading the newspaper", "Making a daily plan", "Fixing something"],
        0,
        ["显性事实理解｜关键词识别"],
        "Ben说'I always read the newspaper at breakfast.'，他每天早上看报纸，而Daisy说的是修背包。"
    ),
    make_qs(
        "You will hear two people talking about a recent trip.",
        "021401-01.mp3",
        "Whose seat needed fixing on the bus?",
        ["Otis's seat", "Smith's seat", "Johnny's seat"],
        2,
        ["显性事实理解｜关键词识别"],
        "Johnny说'I had to repair a broken seat on the bus!'，他在公交车上修了座位。Otis和Smith提到了其他事情。"
    ),
    make_qs(
        "You will hear two people describing what they are carrying.",
        "021401-02.mp3",
        "What does Lucy need to do with her bag?",
        ["Read it on the train", "Repair the zip", "Find a quiet seat for it"],
        1,
        ["显性事实理解｜关键词识别"],
        "Lucy说'I need to repair this old backpack. The zip is broken.'，她的背包拉链坏了需要修理。"
    ),
    make_qs(
        "You will hear two people talking about their weekend.",
        "021401-03.mp3",
        "What does Ben plan to do this weekend?",
        ["Buy a new backpack for hiking", "Read the newspaper at home", "Fix the garden seat"],
        2,
        ["听力细节理解"],
        "Ben说'I'm going to repair the garden seat.'，他打算修理花园椅子。选项C为正确答案。"
    ),
    make_qs(
        "You will hear two people in a waiting room.",
        "021401-04.mp3",
        "What delayed Lucy this morning?",
        ["She forgot her newspaper", "Her backpack strap broke", "She couldn't find a seat"],
        1,
        ["听力细节理解"],
        "Lucy说'my backpack strap broke and I had to repair it.'，背包带断了所以迟到了。"
    ),
]

QSID_021401_FIRST_DIALOGUES = [
    """Ben: Hi, Lucy. I always read the newspaper at breakfast. It's a good way to start the day.
Lucy: That's nice, Ben. I plan my day while I eat. I write a list of things to do.""",
    """Johnny: My plan was to relax on the trip, but I had to repair a broken seat on the bus!
Otis: Oh no, Johnny! I bought a new backpack for the trip. My old one was too small.""",
    """Lucy: I need to repair this old backpack. The zip is broken.
Ben: Oh dear, Lucy. My plan is to find a quiet seat and finish my book.""",
    """Ben: I'm going to repair the garden seat this weekend. It's been wobbly for weeks.
Lucy: Good idea, Ben. My plan is to stay home and read the Sunday newspaper.""",
    """Lucy: Sorry I'm late. My backpack strap broke and I had to repair it.
Ben: No worries, Lucy. I wish I had a newspaper to read while waiting. This is so boring.""",
]

for i, d in enumerate(QSID_021401_FIRST_DIALOGUES):
    QSID_021401_FIRST[i]["dialogue"] = d

QSID_021401_FIRST_BLOCK = make_block("021401", QSID_021401_FIRST)

QSID_021401_SECOND = [
    make_qs(
        "You will hear two people talking about what they did yesterday.",
        "021401-05.mp3",
        "Whose plan was to prepare for next week's trip?",
        ["Ben's plan to prepare for next week's trip", "Skylar's plan to fix the backpack", "Lucy's plan to read in the park"],
        0,
        ["显性事实理解｜关键词识别"],
        "Ben说'I had to plan my trip for next week.'，他在为下周旅行做准备。选项A为正确答案。"
    ),
    make_qs(
        "You will hear two people talking about things they need.",
        "021401-06.mp3",
        "What does Lucy say she needs to do?",
        ["Repair a broken seat", "Buy a new backpack for school", "Plan a weekend visit"],
        0,
        ["听力细节理解"],
        "Lucy说'I should repair this seat.'，她需要修椅子。选项A为正确答案。"
    ),
    make_qs(
        "You will hear two people talking about where they are.",
        "021401-07.mp3",
        "Where is Ben most likely?",
        ["At a bus stop", "In a repair shop", "At home or in a park"],
        2,
        ["听力细节理解"],
        "Ben说'I've put my backpack on this seat and I'm looking for my plan.'，他在公园或家里的座位上整理计划。"
    ),
    make_qs(
        "You will hear two people talking about their problems.",
        "021401-08.mp3",
        "What problem does Ben describe?",
        ["He can't read the newspaper without glasses", "He forgot his backpack with the map", "His newspaper got wet on the seat"],
        1,
        ["听力细节理解"],
        "Ben说'My plan failed because I forgot my backpack with the map.'，他忘了带装地图的背包。选项B为正确答案。"
    ),
    make_qs(
        "You will hear two people giving advice.",
        "021401-09.mp3",
        "What does Ben advise about backpacks?",
        ["Always plan your day first", "Don't put heavy books in a cheap backpack", "Use a newspaper to sit on a dirty seat"],
        1,
        ["听力细节理解"],
        "Ben说'Don't put heavy books in a cheap backpack; it might break.'，他建议不要把重书放进便宜的背包。"
    ),
]

QSID_021401_SECOND_DIALOGUES = [
    """Ben: Hi, Lucy. I had to plan my trip for next week. I looked at a map and wrote a list.
Lucy: That sounds organised, Ben. I tried to repair my old backpack. It had a hole, but I fixed it.""",
    """Lucy: I should repair this seat. It's broken and uncomfortable.
Ben: Oh, Lucy. I need a new backpack for school. My old one is too small.""",
    """Ben: I've put my backpack on this seat and I'm looking for my plan.
Lucy: That looks relaxing, Ben. I'm sitting on a comfortable seat over here, planning my holiday.""",
    """Ben: My plan failed because I forgot my backpack with the map.
Lucy: That's bad luck, Ben. I can't read the newspaper. I need to repair my glasses first.""",
    """Ben: Don't put heavy books in a cheap backpack; it might break.
Lucy: That's good advice, Ben. You should also always plan your day. It helps a lot.""",
]

for i, d in enumerate(QSID_021401_SECOND_DIALOGUES):
    QSID_021401_SECOND[i]["dialogue"] = d

QSID_021401_SECOND_BLOCK = make_block("021401", QSID_021401_SECOND)

# ============================================================
# 021501 - 访客话题 (visitor/clever/serious/mad/sorry/welcome/laugh)
# first: 5 Qs | second: 5 Qs
# ============================================================
QSID_021501_FIRST = [
    make_qs(
        "You will hear two people talking about a recent visitor.",
        "021501-00.mp3",
        "Which speaker felt annoyed at first?",
        ["Ben", "Lucy", "Daisy"],
        1,
        ["显性事实理解｜关键词识别"],
        "Lucy说'I was a bit mad at first because my visitor arrived late, but in the end, I was happy to welcome him.'，她起初生气但后来很开心。Daisy不在对话中，是干扰项。"
    ),
    make_qs(
        "You will hear two people talking about inviting someone.",
        "021501-01.mp3",
        "What does Ben say about inviting more guests?",
        ["He wants to invite his cousin", "He feels sorry about the party", "He can't invite any more because the house is full"],
        2,
        ["听力细节理解"],
        "Ben说'I'm sorry, but we can't invite any more guests. The house is full.'，房子满了无法邀请更多客人。选项C为正确答案。"
    ),
    make_qs(
        "You will hear two people describing a guest.",
        "021501-02.mp3",
        "Whose guest seemed serious at first but later became friendly?",
        ["Smith's guest changed from serious to friendly", "Lucy's guest told clever stories", "Ben's guest was serious and quiet"],
        0,
        ["显性事实理解｜关键词识别"],
        "对话中Smith说'The visitor seemed very serious at first, but later he was very friendly.'，是Smith的客人性格变化。选项A为正确答案。"
    ),
    make_qs(
        "You will hear two people talking about a party.",
        "021501-03.mp3",
        "What did Ben forget to do for his party?",
        ["He forgot to prepare enough food", "He forgot to invite one friend", "He forgot to welcome a guest"],
        1,
        ["听力细节理解"],
        "Ben说'I was mad because I forgot to invite one friend. I said sorry to her later.'，他忘邀请一位朋友。选项B为正确答案。"
    ),
    make_qs(
        "You will hear two people talking about their feelings.",
        "021501-04.mp3",
        "What does Lucy say about making up with a friend?",
        ["She feels sorry for a serious-looking guest", "She thinks it's clever to welcome all visitors", "She's not mad anymore after saying sorry"],
        2,
        ["听力细节理解"],
        "Lucy说'I'm not mad anymore. I said sorry, and now my friend is welcome to visit.'，道歉后两人和好了。选项C为正确答案。"
    ),
]

QSID_021501_FIRST_DIALOGUES = [
    """Ben: Hi, Lucy. We had a visitor last week. He was clever, but he was also quite serious.
Lucy: Oh, Ben. My guest made me laugh a lot. I'm sorry he had to leave so soon.""",
    """Ben: I'm sorry, but we can't invite any more guests. The house is full.
Lucy: That's okay, Ben. I want to invite my cousin. He's very clever and always makes us laugh.""",
    """Smith: The visitor seemed very serious at first, but later he was very friendly.
Lucy: That's nice, Smith. Our guest was so clever. He told funny stories that made everyone laugh.""",
    """Ben: I was mad because I forgot to invite one friend. I said sorry to her later.
Lucy: Oh dear, Ben. Every guest was welcome at my party. It was great to hear them all laugh together.""",
    """Lucy: I'm not mad anymore. I said sorry, and now my friend is welcome to visit.
Ben: That's good, Lucy. I feel sorry for our guest. He looked serious and didn't laugh much.""",
]

for i, d in enumerate(QSID_021501_FIRST_DIALOGUES):
    QSID_021501_FIRST[i]["dialogue"] = d

QSID_021501_FIRST_BLOCK = make_block("021501", QSID_021501_FIRST)

QSID_021501_SECOND = [
    make_qs(
        "You will hear two people talking about something they did at school.",
        "021501-05.mp3",
        "Who will try to be more careful next time?",
        ["Ben", "Lucy", "Skylar"],
        0,
        ["显性事实理解｜关键词识别"],
        "Ben说'I'll be more careful next time.'，他说下次会更仔细。Skylar不在对话中，是干扰项。"
    ),
    make_qs(
        "You will hear two people talking about learning something new.",
        "021501-06.mp3",
        "Whose book had a printing error?",
        ["Daisy's book", "Otis's book", "Ben's book"],
        1,
        ["显性事实理解｜关键词识别"],
        "Otis说'I noticed a mistake in the book. The reason was a printing error.'，Ben在对话中提到了学画，Otis发现了印刷错误。"
    ),
    make_qs(
        "You will hear two people talking about their plans.",
        "021501-07.mp3",
        "What does Ben want to do in the future?",
        ["Write a story because he loves reading", "Work with new technology", "Read instructions more carefully"],
        0,
        ["听力细节理解"],
        "Ben说'I want to write a story. The reason is I love reading.'，他的计划是写故事。选项A为正确答案。"
    ),
    make_qs(
        "You will hear two people giving advice.",
        "021501-08.mp3",
        "What does Lucy say about copying?",
        ["Always read the instruction before starting", "Be careful with new technology", "If you copy someone's work, you won't learn"],
        2,
        ["听力细节理解"],
        "Lucy说'If you copy someone's work, you won't learn.'，抄袭不能帮助学习。选项C为正确答案。"
    ),
    make_qs(
        "You will hear two people talking about a problem they solved.",
        "021501-09.mp3",
        "How did Ben find his mistake?",
        ["He copied the text carefully again", "He used a computer program", "He asked the teacher for clear instruction"],
        1,
        ["听力细节理解"],
        "Ben说'I used a computer program to work out a difficult sum. The technology found my mistake.'，他用电脑程序发现了错误。选项B为正确答案。"
    ),
]

QSID_021501_SECOND_DIALOGUES = [
    """Ben: Hi, Lucy. I made a mistake in my maths homework. I didn't read the instruction carefully. I'll be more careful next time.
Lucy: I understand, Ben. I didn't notice the reason for the new classroom rule. I just copied it from the board. I should ask the teacher in the future.""",
    """Otis: I noticed a mistake in the book. The reason was a printing error. I'll tell the teacher about it in the future.
Ben: Good catch, Otis. I followed the instruction carefully to use the new app. I didn't want to make a mistake. It worked out well!""",
    """Ben: I want to write a story. The reason is I love reading. I'll copy the style of my favourite author, but I won't make the same mistake he did.
Lucy: That's a great plan, Ben. My plan for the future is to work with new technology. I need to be careful and study hard to make it work out.""",
    """Lucy: If you copy someone's work, you won't learn. The reason is you need to work out problems yourself to understand.
Ben: That's so true, Lucy. Always read the instruction before you start. That's the best way to avoid a mistake.""",
    """Ben: I used a computer program to work out a difficult sum. The technology found my mistake. I was more careful after that.
Lucy: That's clever, Ben. I had to copy a long text. I did it carefully to avoid any mistake. It took time, but it worked out in the end.""",
]

for i, d in enumerate(QSID_021501_SECOND_DIALOGUES):
    QSID_021501_SECOND[i]["dialogue"] = d

QSID_021501_SECOND_BLOCK = make_block("021501", QSID_021501_SECOND)

# ============================================================
# 021601 - 体验话题 (strange/quiet/noisy/heavy/fresh/drop)
# first: 5 Qs | second: empty
# ============================================================
QSID_021601_FIRST = [
    make_qs(
        "You will hear two people talking about their morning.",
        "021601-00.mp3",
        "Who had a strange experience this morning?",
        ["Ben", "Lucy", "Skylar"],
        0,
        ["显性事实理解｜关键词识别"],
        "Ben说'I had a very strange morning. I saw a cat wearing a hat!'，他的早晨非常奇怪。Skylar不在对话中，是干扰项。"
    ),
    make_qs(
        "You will hear two people talking about a place they visited.",
        "021601-01.mp3",
        "What does Lucy say about the library?",
        ["It was very crowded", "It is quiet and she can read there", "It was too noisy with traffic"],
        1,
        ["听力细节理解"],
        "Lucy说'I love our local library. It's quiet and I can read there.'，图书馆安静适合读书。"
    ),
    make_qs(
        "You will hear two people talking about something that happened.",
        "021601-02.mp3",
        "Whose box fell and made a mess?",
        ["Johnny's box", "Ben's box", "Lucy's box"],
        0,
        ["显性事实理解｜关键词识别"],
        "Johnny说'I was carrying a box and I let it drop. What a mess!'，他的盒子掉了，弄得很乱。Ben提到了noise，Lucy提到了bread。"
    ),
    make_qs(
        "You will hear two people describing how they feel.",
        "021601-03.mp3",
        "What is Lucy complaining about?",
        ["A suitcase that is too heavy", "Streets that are too crowded", "A room that is too noisy"],
        2,
        ["听力细节理解"],
        "Lucy说'I can't study here. This room is too noisy.'，她嫌房间太吵无法学习。"
    ),
    make_qs(
        "You will hear two people talking about their shopping.",
        "021601-04.mp3",
        "What warning does Ben give at the market?",
        ["Don't buy strange fruit", "Be careful with the eggs, don't drop them", "Buy fresh vegetables instead"],
        1,
        ["听力细节理解"],
        "Ben说'Be careful with that bag! Don't drop the eggs.'，他在警告不要把鸡蛋掉了。"
    ),
]

QSID_021601_FIRST_DIALOGUES = [
    """Ben: Hi, Lucy. I had a very strange morning. I saw a cat wearing a hat!
Lucy: Wow, Ben! I went to the market early. The air was so fresh and nice.""",
    """Lucy: I love our local library. It's quiet and I can read there.
Ben: That sounds lovely, Lucy. I went to the new park. It was very crowded with people.""",
    """Johnny: I was carrying a box and I let it drop. What a mess!
Ben: Oh no, Johnny! I heard a very strange noise last night. It was like a whistle.""",
    """Lucy: I can't study here. This room is too noisy.
Ben: I know what you mean, Lucy. This suitcase is too heavy for me to lift.""",
    """Ben: Be careful with that bag! Don't drop the eggs.
Lucy: Thanks, Ben. I bought some strange fruit. I've never seen it before.""",
]

for i, d in enumerate(QSID_021601_FIRST_DIALOGUES):
    QSID_021601_FIRST[i]["dialogue"] = d

QSID_021601_FIRST_BLOCK = make_block("021601", QSID_021601_FIRST)

# ============================================================
# 021701 - 周末话题 (basketball/bookcase/draw/machine/invention)
# first: 5 Qs | second: empty
# ============================================================
QSID_021701_FIRST = [
    make_qs(
        "You will hear two people talking about what they did last weekend.",
        "021701-00.mp3",
        "Who played basketball last weekend?",
        ["Ben", "Lucy", "Skylar"],
        0,
        ["显性事实理解｜关键词识别"],
        "Ben说'Last weekend, I played basketball twice with my friends.'，他上周打了篮球。Skylar不在对话中，是干扰项。"
    ),
    make_qs(
        "You will hear two people talking about their hobbies.",
        "021701-01.mp3",
        "Whose hobby needs a bigger bookcase?",
        ["Daisy's hobby", "Smith's hobby", "Johnny's hobby"],
        1,
        ["显性事实理解｜关键词识别"],
        "Smith说'I enjoy reading. I have so many books that I need a bigger bookcase.'，他书太多需要更大的书架。Johnny不在对话中，是干扰项。"
    ),
    make_qs(
        "You will hear two people talking about things they saw.",
        "021701-02.mp3",
        "What did Ben read about that was from long ago?",
        ["A clever machine that can draw", "A basketball game on TV", "A great invention from many years ago"],
        2,
        ["听力细节理解"],
        "Ben说'I read about a great invention in a book. Someone made it many years ago.'，他读到一项古老的发明。选项C为正确答案。"
    ),
    make_qs(
        "You will hear two people talking about what they made or did.",
        "021701-03.mp3",
        "What did Lucy make for her room?",
        ["A small bookcase", "A funny drawing of a machine", "A basketball drawing"],
        0,
        ["听力细节理解"],
        "Lucy说'I made a small bookcase for my room. It was hard work!'，她为自己房间做了个小书架。"
    ),
    make_qs(
        "You will hear two people talking about their plans.",
        "021701-04.mp3",
        "What does Ben want to learn to draw?",
        ["A famous person from long ago", "A basketball", "An old machine"],
        1,
        ["听力细节理解"],
        "Ben说'I want to learn how to draw a basketball. It seems difficult.'，他想学画篮球。"
    ),
]

QSID_021701_FIRST_DIALOGUES = [
    """Ben: Hi, Lucy. Last weekend, I played basketball twice with my friends. It was so much fun.
Lucy: That sounds great, Ben. I went to the library and read some interesting books. I also helped my dad build a new bookcase.""",
    """Smith: My hobby is drawing. I like to draw pictures of people and places.
Ben: That's nice, Smith. I enjoy reading. I have so many books that I need a bigger bookcase.""",
    """Ben: I read about a great invention in a book. Someone made it many years ago.
Lucy: That's interesting, Ben. I saw a very clever machine yesterday. It can draw pictures by itself!""",
    """Lucy: I made a small bookcase for my room. It was hard work!
Ben: Well done, Lucy. I drew a picture of a funny machine. My teacher liked it.""",
    """Ben: I want to learn how to draw a basketball. It seems difficult.
Lucy: That's a fun goal, Ben. I plan to read a book about a famous person from long ago.""",
]

for i, d in enumerate(QSID_021701_FIRST_DIALOGUES):
    QSID_021701_FIRST[i]["dialogue"] = d

QSID_021701_FIRST_BLOCK = make_block("021701", QSID_021701_FIRST)

# ============================================================
# 021801 - 出行话题 (battery/shop/theatre/show/midday/bright/corner/climb)
# first: 5 Qs | second: 5 Qs
# ============================================================
QSID_021801_FIRST = [
    make_qs(
        "You will hear two people talking about what they did in the morning.",
        "021801-00.mp3",
        "Whose toy car needed a new battery?",
        ["Ben's toy car", "Lucy's toy car", "Daisy's toy car"],
        0,
        ["显性事实理解｜关键词识别"],
        "Ben说'I needed a new battery for my toy car. I went to the shop at midday to buy one.'，他的玩具车需要新电池。Daisy不在对话中，是干扰项。"
    ),
    make_qs(
        "You will hear two people talking about their weekend activities.",
        "021801-01.mp3",
        "What did Ben and his friend do at the theatre?",
        ["Watched a special play", "Climbed a tall tree", "Fixed a phone"],
        0,
        ["听力细节理解"],
        "Ben说'We went to the theatre. It was a special play and very interesting.'，他们去剧院看了一场特别的戏剧。"
    ),
    make_qs(
        "You will hear two people describing a place they visited.",
        "021801-02.mp3",
        "What does Lucy mention about the place she visited?",
        ["It was very bright at midday", "It had a quiet corner to sit and read", "The old tower was closed"],
        1,
        ["听力细节理解"],
        "Lucy说'I liked the quiet corner best. It was a special place to sit and read.'，她最喜欢安静的角落。"
    ),
    make_qs(
        "You will hear two people talking about something that happened.",
        "021801-03.mp3",
        "What did Lucy's torch help them do?",
        ["Meet a friend at the library", "See in the dark", "Climb a hill in the rain"],
        1,
        ["听力细节理解"],
        "Lucy说'The special battery in my torch made it very bright. It helped us see in the dark.'，手电筒帮他们在黑暗中看清。"
    ),
    make_qs(
        "You will hear two people talking about different problems.",
        "021801-04.mp3",
        "What problem did Ben have?",
        ["He lost his keys in the kitchen", "He was late for a film at the theatre", "His watch stopped because the battery was old"],
        2,
        ["听力细节理解"],
        "Ben说'My watch stopped because the battery was old. I bought a new one after lunch.'，他的手表没电了。选项C为正确答案。"
    ),
]

QSID_021801_FIRST_DIALOGUES = [
    """Ben: Hi, Lucy. I needed a new battery for my toy car. I went to the shop at midday to buy one.
Lucy: Oh, Ben. I arrived at the theatre early to get a good seat for the special show.""",
    """Ben: We went to the theatre. It was a special play and very interesting.
Lucy: That sounds fun, Ben. I helped my brother climb a tall tree in the park. It was exciting!""",
    """Lucy: I liked the quiet corner best. It was a special place to sit and read.
Ben: That's nice, Lucy. I arrived just before midday. The room was very bright because of the big windows.""",
    """Lucy: The special battery in my torch made it very bright. It helped us see in the dark.
Ben: That's useful, Lucy. I was sitting in the corner of the library when my friend arrived. We studied together.""",
    """Ben: My watch stopped because the battery was old. I bought a new one after lunch.
Lucy: That's annoying, Ben. I couldn't find my keys. They were in the bright corner of the kitchen, under a newspaper.""",
]

for i, d in enumerate(QSID_021801_FIRST_DIALOGUES):
    QSID_021801_FIRST[i]["dialogue"] = d

QSID_021801_FIRST_BLOCK = make_block("021801", QSID_021801_FIRST)

QSID_021801_SECOND = [
    make_qs(
        "You will hear two people talking about a surprise party.",
        "021801-05.mp3",
        "Who felt very excited about the party?",
        ["Lucy", "Ben", "Daisy"],
        0,
        ["显性事实理解｜关键词识别"],
        "Lucy说'I was so excited about the party! I thought everyone would forget, but they all came.'，她非常兴奋。Daisy不在对话中，是干扰项。"
    ),
    make_qs(
        "You will hear two people talking about a school play.",
        "021801-06.mp3",
        "What did Ben feel during the play?",
        ["He felt nervous", "His heart was racing with excitement", "He forgot one of his lines"],
        1,
        ["听力细节理解"],
        "Ben说'I felt my heart racing when I was on stage. It was exciting!'，他在舞台上心跳加速非常激动。"
    ),
    make_qs(
        "You will hear two people talking about their weekend.",
        "021801-07.mp3",
        "Why was Lucy's Sunday brilliant?",
        ["She finally got to rest", "She visited her grandma", "The weather was brilliant"],
        1,
        ["听力细节理解"],
        "Lucy说'I was excited to visit my grandma. I felt my heart was full of joy.'，她周日去看了奶奶很开心。"
    ),
    make_qs(
        "You will hear two people talking about a football match.",
        "021801-08.mp3",
        "Why did Ben think the game was brilliant?",
        ["His team scored the first goal", "His team played well all game", "The result was better than expected"],
        0,
        ["听力细节理解"],
        "Ben说'It was a brilliant game! I felt so excited when we scored the first goal.'，球队进了第一个球让他很兴奋。"
    ),
    make_qs(
        "You will hear two people talking about a test.",
        "021801-09.mp3",
        "Who felt positive after the test?",
        ["Johnny", "Ben", "Lucy"],
        2,
        ["显性事实理解｜关键词识别"],
        "Lucy说'I felt excited after the test because I think it went brilliantly.'，她考后感觉很积极。Johnny感到nervous，Lucy感到excited。"
    ),
]

QSID_021801_SECOND_DIALOGUES = [
    """Lucy: I was so excited about the party! I thought everyone would forget, but they all came.
Ben: That's wonderful, Lucy. I suppose it was a brilliant idea. I felt my heart beating fast when I saw the cake.""",
    """Ben: I felt my heart racing when I was on stage. It was exciting!
Lucy: I know the feeling, Ben. I suppose the play was brilliant. My friend said I was good, but I felt a bit nervous.""",
    """Lucy: I was excited to visit my grandma. I felt my heart was full of joy.
Ben: That's so sweet, Lucy. I felt tired on Saturday. I suppose I forgot to rest. But Sunday was brilliant!""",
    """Ben: It was a brilliant game! I felt so excited when we scored the first goal.
Lucy: Lucky you, Ben. I felt disappointed because our team lost. I suppose we forgot how to play well.""",
    """Lucy: I felt excited after the test because I think it went brilliantly.
Ben: That's great, Lucy. I felt my heart beat quickly before the test. I was so nervous!""",
]

for i, d in enumerate(QSID_021801_SECOND_DIALOGUES):
    QSID_021801_SECOND[i]["dialogue"] = d

QSID_021801_SECOND_BLOCK = make_block("021801", QSID_021801_SECOND)

# ============================================================
# 022101 - 活动话题 (race/factory/skate/port/noise/ship)
# first: 5 Qs | second: empty
# ============================================================
QSID_022101_FIRST = [
    make_qs(
        "You will hear two people talking about their weekend.",
        "022101-00.mp3",
        "Who went to watch a boat race at the port?",
        ["Ben", "Lucy", "Daisy"],
        0,
        ["显性事实理解｜关键词识别"],
        "Ben说'I went to watch a boat race at the port. It was exciting!'，他去港口看了赛船。Daisy不在对话中，是干扰项。"
    ),
    make_qs(
        "You will hear two people talking about sounds they heard.",
        "022101-01.mp3",
        "Where did the noise Lucy heard come from?",
        ["At the port, from boats", "Near the factory", "At home, a ball hit the window"],
        2,
        ["听力细节理解"],
        "Lucy说'I heard a loud noise when a ball hit the window.'，球撞到窗户发出噪音。选项C为正确答案。"
    ),
    make_qs(
        "You will hear two people talking about things they saw.",
        "022101-02.mp3",
        "What did Ben see at the factory?",
        ["A big ship going through the port", "Workers making things inside", "Children having a race on skates"],
        1,
        ["听力细节理解"],
        "Ben说'I saw workers making things inside the factory.'，他在工厂看到了工人在制造东西。"
    ),
    make_qs(
        "You will hear two people talking about problems they had.",
        "022101-03.mp3",
        "What kept Lucy awake last night?",
        ["She fell down while skating", "The noise from the port", "She got lost in the factory"],
        1,
        ["听力细节理解"],
        "Lucy说'The noise from the port kept me awake last night.'，港口的噪音让她睡不着。"
    ),
    make_qs(
        "You will hear two people talking about their favourite activities.",
        "022101-04.mp3",
        "What does Ben enjoy doing most?",
        ["Watching boat races", "Skating fast", "Visiting the port to see boats"],
        0,
        ["听力细节理解"],
        "Ben说'I love watching boat races. They are the best!'，他最喜欢看船赛。"
    ),
]

QSID_022101_FIRST_DIALOGUES = [
    """Ben: Hi, Lucy. I went to watch a boat race at the port. It was exciting!
Lucy: That sounds fun, Ben. I visited a factory with my class. It was noisy but interesting.""",
    """Lucy: I heard a loud noise when a ball hit the window.
Ben: Oh dear, Lucy. The sound of boats at the port was very loud this morning.""",
    """Ben: I saw workers making things inside the factory.
Lucy: That's interesting, Ben. I saw a big ship go through the port. It was huge!""",
    """Lucy: The noise from the port kept me awake last night.
Ben: That's too bad, Lucy. My skate hit a stone and I fell down.""",
    """Ben: I love watching boat races. They are the best!
Lucy: I can see why, Ben. I enjoy skating fast. It feels like flying.""",
]

for i, d in enumerate(QSID_022101_FIRST_DIALOGUES):
    QSID_022101_FIRST[i]["dialogue"] = d

QSID_022101_FIRST_BLOCK = make_block("022101", QSID_022101_FIRST)

# ============================================================
# 032501 - 工作话题 (journalist/partner/internet/capital/invitation/company)
# first: 5 Qs | second: empty
# ============================================================
QSID_032501_FIRST = [
    make_qs(
        "You will hear two people talking about their new jobs.",
        "032501-00.mp3",
        "Who works with a partner as a journalist?",
        ["Skylar's job online", "Lucy's job at a big company", "Ben's job as a journalist with a partner"],
        2,
        ["显性事实理解｜关键词识别"],
        "Ben说'My partner and I write stories for a newspaper.'，他和搭档一起工作。选项C为正确答案。"
    ),
    make_qs(
        "You will hear two people talking about their plans for the weekend.",
        "032501-01.mp3",
        "Whose friend sent an invitation to visit the capital?",
        ["Otis's friend", "Lucy's friend", "Daisy's friend"],
        0,
        ["显性事实理解｜关键词识别"],
        "Otis说'I'm going to the capital to visit a museum. I got an invitation from a friend who lives there.'，他的朋友邀请他去首都。Daisy不在对话中。"
    ),
    make_qs(
        "You will hear two people talking about what they like.",
        "032501-02.mp3",
        "What does Ben say about his job?",
        ["He finds history very interesting", "He works as a journalist with different people", "He uses the internet to talk to his partner"],
        1,
        ["听力细节理解"],
        "Ben说'My job is interesting because I'm a journalist. I don't have a fixed partner; I work with different people.'，他的记者工作有趣因为可以和不同的人合作。"
    ),
    make_qs(
        "You will hear two people talking about their work.",
        "032501-03.mp3",
        "Who does all their work online from home?",
        ["Skylar", "Lucy", "Daisy"],
        0,
        ["显性事实理解｜关键词识别"],
        "Skylar说'I work alone at home. I don't have a partner. All my research is done on the internet.'，他所有工作都在网上完成。Daisy不在对话中。"
    ),
    make_qs(
        "You will hear two people talking about recent events.",
        "032501-04.mp3",
        "What did Ben read on the internet?",
        ["About interesting places in the capital", "An interesting story by a famous journalist", "A surprising invitation to be a journalist's partner"],
        1,
        ["听力细节理解"],
        "Ben说'I read an interesting story by a famous journalist on the internet yesterday.'，他在网上读到一位名记者写的有趣故事。"
    ),
]

QSID_032501_FIRST_DIALOGUES = [
    """Ben: Hi, Lucy. I started working as a journalist last month. My partner and I write stories for a newspaper. It's very interesting.
Lucy: That's exciting, Ben. I got an invitation to work for a big company in the capital. I'm excited to move there.""",
    """Otis: I'm going to the capital to visit a museum. I got an invitation from a friend who lives there.
Lucy: How nice, Otis. My weekend will be boring. I have to work with my partner on a project using the internet.""",
    """Ben: My job is interesting because I'm a journalist. I don't have a fixed partner; I work with different people.
Lucy: That's great, Ben. I think history is very interesting. I read a lot about different capitals on the internet.""",
    """Skylar: I work alone at home. I don't have a partner. All my research is done on the internet.
Lucy: That sounds peaceful, Skylar. I work as a journalist in the capital. Sometimes it's interesting, sometimes it's not.""",
    """Ben: I read an interesting story by a famous journalist on the internet yesterday.
Lucy: Oh really, Ben? My partner and I visited the capital. We saw many interesting places.""",
]

for i, d in enumerate(QSID_032501_FIRST_DIALOGUES):
    QSID_032501_FIRST[i]["dialogue"] = d

QSID_032501_FIRST_BLOCK = make_block("032501", QSID_032501_FIRST)

# ============================================================
# 032901 - 日常话题 (shower/exercise/hobby/boss/offer/easy/soft drink)
# first: 5 Qs | second: empty
# ============================================================
QSID_032901_FIRST = [
    make_qs(
        "You will hear two people talking about their morning routines.",
        "032901-00.mp3",
        "Who does exercise in the morning?",
        ["Ben", "Lucy", "Skylar"],
        0,
        ["显性事实理解｜关键词识别"],
        "Ben说'I always take a quick shower in the morning. Then I do some exercise, like running, before breakfast.'，他早上会锻炼。Skylar不在对话中，是干扰项。"
    ),
    make_qs(
        "You will hear two people talking about their jobs.",
        "032901-01.mp3",
        "Whose job is also their hobby?",
        ["Otis's job", "Daisy's job", "Ben's job"],
        2,
        ["显性事实理解｜关键词识别"],
        "Ben说'My hobby is my job! I teach people how to exercise correctly. It's fun to share my passion.'，他的爱好成为了工作。Daisy在café工作，Ben教人锻炼。"
    ),
    make_qs(
        "You will hear two people talking about what they like to do after work.",
        "032901-02.mp3",
        "What does Lucy prefer to do after work?",
        ["Take a long, hot shower and read", "Meet friends for a run", "Watch TV because it's easy"],
        0,
        ["听力细节理解"],
        "Lucy说'After work, I love to relax. A long, hot shower is the best. Then I might read a book.'，她下班后喜欢淋浴和看书。"
    ),
    make_qs(
        "You will hear two people talking about helping others.",
        "032901-03.mp3",
        "How does Ben help customers at his café job?",
        ["He drives friends home after the photography club", "He offers tired customers a free soft drink", "He cooks for his family"],
        1,
        ["听力细节理解"],
        "Ben说'if a customer looks tired, I sometimes offer them a free soft drink. My boss says it's a good idea.'，他在café工作时会送疲惫的客人免费饮料。"
    ),
    make_qs(
        "You will hear two people talking about their plans for the weekend.",
        "032901-04.mp3",
        "Who has to work on Saturday because their boss asked?",
        ["Smith", "Johnny", "Lucy"],
        1,
        ["显性事实理解｜关键词识别"],
        "Johnny说'My boss asked me to work on Saturday. It won't be easy, but I said yes.'，老板要求他周六工作。Lucy打算休息。"
    ),
]

QSID_032901_FIRST_DIALOGUES = [
    """Ben: Hi, Lucy. I always take a quick shower in the morning. Then I do some exercise, like running, before breakfast.
Lucy: That's healthy, Ben. My morning is easy. I just have a soft drink and check my emails. My boss is always the first to write.""",
    """Ben: My hobby is my job! I teach people how to exercise correctly. It's fun to share my passion.
Lucy: That's great, Ben. My boss is very kind. He often offers to help me with difficult tasks, which makes my work much easier.""",
    """Lucy: After work, I love to relax. A long, hot shower is the best. Then I might read a book.
Ben: That sounds nice, Lucy. I usually meet friends. We often go for a run for exercise. Sometimes we just have a soft drink and chat.""",
    """Ben: At the café, if a customer looks tired, I sometimes offer them a free soft drink. My boss says it's a good idea.
Lucy: That's so kind, Ben. I always offer to drive my friends home after our photography club. It's no problem for me.""",
    """Johnny: My boss asked me to work on Saturday. It won't be easy, but I said yes. I hope he offers to pay extra.
Lucy: Oh dear, Johnny. I need to do some exercise, so I'll probably go to the gym. But first, a nice shower!""",
]

for i, d in enumerate(QSID_032901_FIRST_DIALOGUES):
    QSID_032901_FIRST[i]["dialogue"] = d

QSID_032901_FIRST_BLOCK = make_block("032901", QSID_032901_FIRST)

# ============================================================
# Record ID -> data mapping
# ============================================================
RECORD_DATA = {
    "021301": {
        "record_id": "recvjufKJO8d0O",
        "first_block": QSID_021301_FIRST_BLOCK,
        "second_block": QSID_021301_SECOND_BLOCK,
        "first_qs_list": QSID_021301_FIRST,
        "second_qs_list": QSID_021301_SECOND,
    },
    "021401": {
        "record_id": "recvjufM763ijb",
        "first_block": QSID_021401_FIRST_BLOCK,
        "second_block": QSID_021401_SECOND_BLOCK,
        "first_qs_list": QSID_021401_FIRST,
        "second_qs_list": QSID_021401_SECOND,
    },
    "021501": {
        "record_id": "recvjufM76lEsW",
        "first_block": QSID_021501_FIRST_BLOCK,
        "second_block": QSID_021501_SECOND_BLOCK,
        "first_qs_list": QSID_021501_FIRST,
        "second_qs_list": QSID_021501_SECOND,
    },
    "021601": {
        "record_id": "recvjufM76hNv5",
        "first_block": QSID_021601_FIRST_BLOCK,
        "second_block": {},
        "first_qs_list": QSID_021601_FIRST,
        "second_qs_list": [],
    },
    "021701": {
        "record_id": "recvjufM76eMKs",
        "first_block": QSID_021701_FIRST_BLOCK,
        "second_block": {},
        "first_qs_list": QSID_021701_FIRST,
        "second_qs_list": [],
    },
    "021801": {
        "record_id": "recvjufM76lRHQ",
        "first_block": QSID_021801_FIRST_BLOCK,
        "second_block": QSID_021801_SECOND_BLOCK,
        "first_qs_list": QSID_021801_FIRST,
        "second_qs_list": QSID_021801_SECOND,
    },
    "022101": {
        "record_id": "recvjufM76o6of",
        "first_block": QSID_022101_FIRST_BLOCK,
        "second_block": {},
        "first_qs_list": QSID_022101_FIRST,
        "second_qs_list": [],
    },
    "032501": {
        "record_id": "recvjufM76k4dx",
        "first_block": QSID_032501_FIRST_BLOCK,
        "second_block": {},
        "first_qs_list": QSID_032501_FIRST,
        "second_qs_list": [],
    },
    "032901": {
        "record_id": "recvjufM76frUP",
        "first_block": QSID_032901_FIRST_BLOCK,
        "second_block": {},
        "first_qs_list": QSID_032901_FIRST,
        "second_qs_list": [],
    },
}

def main():
    mode = sys.argv[1] if len(sys.argv) > 1 else "dry"
    
    for qsid, data in RECORD_DATA.items():
        record_id = data["record_id"]
        first_block = data["first_block"]
        second_block = data["second_block"]
        first_qs = data["first_qs_list"]
        second_qs = data["second_qs_list"]
        
        # Build jsonData
        json_data = {"first": first_block, "second": second_block}
        
        # Build 题目1 text
        q1_text = make_q1_text(first_qs)
        q2_text = make_q1_text(second_qs) if second_qs else ""
        
        # Remove dialogue key from question set for jsonData
        for q in first_block["questionSet"]:
            q.pop("dialogue", None)
        if second_block and isinstance(second_block, dict) and "questionSet" in second_block:
            for q in second_block["questionSet"]:
                q.pop("dialogue", None)
        
        fields = {
            "jsonData": json.dumps(json_data, ensure_ascii=False),
            "题目1": q1_text,
            "题目2": q2_text,
        }
        
        fields_json = json.dumps(fields, ensure_ascii=False)
        
        print(f"\n{'='*60}")
        print(f"QSID: {qsid} | Record: {record_id}")
        print(f"First questions: {len(first_qs)}")
        print(f"Second questions: {len(second_qs)}")
        
        # Verify answer distribution
        answers_first = [q["answer"][0] for q in first_qs]
        a_counts = {0: answers_first.count(0), 1: answers_first.count(1), 2: answers_first.count(2)}
        print(f"First answer distribution: A={a_counts[0]}, B={a_counts[1]}, C={a_counts[2]}")
        if max(a_counts.values()) > 2:
            print(f"  ⚠️ WARNING: answer not evenly distributed!")
        
        if second_qs:
            answers_second = [q["answer"][0] for q in second_qs]
            s_counts = {0: answers_second.count(0), 1: answers_second.count(1), 2: answers_second.count(2)}
            print(f"Second answer distribution: A={s_counts[0]}, B={s_counts[1]}, C={s_counts[2]}")
            if max(s_counts.values()) > 2:
                print(f"  ⚠️ WARNING: answer not evenly distributed!")
        
        if mode == "write":
            result = update_record(record_id, fields_json)
            code = result.get("code", -1)
            if code == 0:
                print(f"  ✅ Write SUCCESS")
            else:
                print(f"  ❌ Write FAILED: {result.get('msg', 'unknown')}")
        elif mode == "dry":
            print(f"  DRY RUN - would write {len(fields_json)} bytes")
            # Save to file for inspection
            fname = f"/tmp/p4_rewrite_{qsid}.json"
            with open(fname, 'w') as f:
                json.dump(json_data, f, ensure_ascii=False, indent=2)
            print(f"  Saved to {fname}")
    
    print(f"\n{'='*60}")
    print("All done!")

if __name__ == "__main__":
    main()
