#!/usr/bin/env python3
"""Generate and write 6 writing/speaking records to unit challenge bitable"""
import requests, json

APP_TOKEN = "CMHSbUUjka3TrUsaxxEc297ongf"
APP_ID = "cli_a931175d41799cc7"
APP_SECRET = "Iw2vEfbjT6GtV0GhbxbZqfQ4nAPtbR14"
BASE = "https://open.feishu.cn/open-apis/bitable/v1"

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

# --- 写作-P1-邮件回复 | 021801 | L2 B级 ---
WRITING_021801_JSON = {
    "first": {
        "category": "writing",
        "type": "writing_email",
        "questionSetID": "021801",
        "textDesc": "Your friend Annie wants to plan a surprise party for her mum. "
                    "Write an email to help her organise it.<br>"
                    "Put these sentences in order to make a clear and helpful email.",
        "optionSetList": [
            "Dear Annie,",
            "Don't tell anyone about the surprise party.",
            "We want to make Mum happy on her birthday.",
            "I think Dad said he will bring the cake.",
            "It must be hard to work every day without a break.",
            "Best wishes,\nYour Friend"
        ],
        "answerSet": [0, 1, 2, 3, 4, 5],
        "ability": ["短消息写作｜邮件/便条", "衔接与连贯｜连词使用"],
        "explanation": "按照邮件格式和事件逻辑排列句子：称呼→说明目的→解释计划→补充细节→表达关心→署名。考察邮件格式规范和逻辑顺序组织能力。"
    },
    "second": {}
}

WRITING_021801_TEXT1 = """【题目描述】
Your friend Annie wants to plan a surprise party for her mum. Write an email to help her organise it.
Put these sentences in order to make a clear and helpful email.

【段落列表】
A. Dear Annie,
B. Don't tell anyone about the surprise party.
C. We want to make Mum happy on her birthday.
D. I think Dad said he will bring the cake.
E. It must be hard to work every day without a break.
F. Best wishes,
Your Friend"""

# --- 写作-P1-邮件回复 | 021901 | L2 B级 ---
WRITING_021901_JSON = {
    "first": {
        "category": "writing",
        "type": "writing_email",
        "questionSetID": "021901",
        "textDesc": "Your friend Tom's pet dog Daisy is lost in the park. "
                    "Write an email to help him search for her.<br>"
                    "Put these sentences in order to make a helpful email.",
        "optionSetList": [
            "Dear Tom,",
            "We must find her before it gets dark!",
            "We need to find Daisy before she runs too far away!",
            "The lake is just in front of the playground.",
            "The gate was open, and Daisy was missing.",
            "Let's search together, while your mum checks the garden, and I check the path.",
            "Best wishes,\nYour Friend"
        ],
        "answerSet": [0, 2, 1, 3, 4, 5, 6],
        "ability": ["短消息写作｜邮件/便条", "衔接与连贯｜连词使用"],
        "explanation": "按照寻物邮件的逻辑排列句子：称呼→表达紧迫性→说明目标→描述位置→解释原因→分工合作→署名。考察事件叙述的逻辑顺序和while/and并列结构的使用。"
    },
    "second": {}
}

WRITING_021901_TEXT1 = """【题目描述】
Your friend Tom's pet dog Daisy is lost in the park. Write an email to help him search for her.
Put these sentences in order to make a helpful email.

【段落列表】
A. Dear Tom,
B. We must find her before it gets dark!
C. We need to find Daisy before she runs too far away!
D. The lake is just in front of the playground.
E. The gate was open, and Daisy was missing.
F. Let's search together, while your mum checks the garden, and I check the path.
G. Best wishes,
Your Friend"""

# --- 写作-P1-邮件回复 | 022001 | L2 B级 ---
WRITING_022001_JSON = {
    "first": {
        "category": "writing",
        "type": "writing_email",
        "questionSetID": "022001",
        "textDesc": "Your friend Lucy wants to make a gift for Grandma's birthday. "
                    "Write an email to help her plan it.<br>"
                    "Put these sentences in order to make a clear email.",
        "optionSetList": [
            "Dear Lucy,",
            "How long does it take you to make a paper card?",
            "Tom is taking the longer route to buy some art supplies.",
            "We still don't know if Grandma will like the surprise.",
            "She always makes special cards for everyone's birthday.",
            "Best wishes,\nYour Friend"
        ],
        "answerSet": [0, 1, 2, 3, 4, 5],
        "ability": ["短消息写作｜邮件/便条", "衔接与连贯｜连词使用"],
        "explanation": "按照邮件逻辑排列句子：称呼→询问→补充信息→表达不确定→说明原因→署名。考察邮件的逻辑衔接和连词使用能力。"
    },
    "second": {}
}

WRITING_022001_TEXT1 = """【题目描述】
Your friend Lucy wants to make a gift for Grandma's birthday. Write an email to help her plan it.
Put these sentences in order to make a clear email.

【段落列表】
A. Dear Lucy,
B. How long does it take you to make a paper card?
C. Tom is taking the longer route to buy some art supplies.
D. We still don't know if Grandma will like the surprise.
E. She always makes special cards for everyone's birthday.
F. Best wishes,
Your Friend"""

# --- 口语-P2-话题讨论 | 021801 | L2 B级 ---
SPEAKING_TOPIC_021801_JSON = {
    "first": {
        "category": "speaking",
        "type": "speaking_topic",
        "asrPrompt": "sick,classmate,help,homework,encourage,goal,dream,support,friend,teamwork",
        "questionSetID": "021801",
        "textDesc": "Look at these pictures about helping others. Talk about what you see "
                    "and share your own ideas about helping and supporting friends.",
        "imageDesc": "Four images show children helping each other: 1st: A child brings a glass of water to a sick friend in bed. 2nd: Two children study together at a desk, one is explaining something. 3rd: A team of children celebrate together with hands raised. 4th: A child gives a present to a sad friend, who then smiles.",
        "textImage": "021801-00.png",
        "questionSet": [
            {
                "content": "What do you do when your friend is sick at home?",
                "ability": ["句型组织", "表达建议"],
                "explanation": "可以用句型 \"We'd better...\" 来给出建议，例如 \"We'd better call him and check how he feels.\" 也可以补充具体行动，如 \"I would bring him homework and tell him to rest well.\""
            },
            {
                "content": "How do you help a classmate who finds homework difficult?",
                "ability": ["句型组织", "表达建议"],
                "explanation": "可以用 \"Let's give him some tips so he can understand better.\" 来表达帮助方式。也可以说 \"I explain the homework step by step and give examples.\""
            },
            {
                "content": "What do you hope for your best friend in the future?",
                "ability": ["句型组织", "表达愿望"],
                "explanation": "可以用 \"I hope he is able to achieve his goals.\" 来表达希望。也可以补充具体内容，如 \"I hope she will go to a good school and make new friends.\""
            },
            {
                "content": "Tell us about a time when someone helped you. How did it feel?",
                "ability": ["句型组织", "经历描述"],
                "explanation": "用过去式描述一次被帮助的经历，例如 \"Last term I couldn't do my maths homework. My friend sat with me after class and helped me finish it. I felt very warm and thankful.\""
            },
            {
                "content": "Why is it important to help others in your class or family?",
                "ability": ["句型组织", "表达观点"],
                "explanation": "可以从合作和友谊角度回答，例如 \"When we help each other, we grow together. Helping makes the team stronger and everyone feels happy.\""
            }
        ]
    },
    "second": {
        "category": "speaking",
        "type": "speaking_topic",
        "asrPrompt": "sick,classmate,help,homework,encourage,goal,dream,support,friend,teamwork",
        "questionSetID": "021801",
        "textDesc": "Now look at these pictures again. Think more deeply about helping others "
                    "and share a different example or experience.",
        "imageDesc": "Same images as above: children helping each other in different situations.",
        "textImage": "021801-01.png",
        "questionSet": [
            {
                "content": "What do you do when your friend is sick at home?",
                "ability": ["句型组织", "表达建议"],
                "explanation": "也可以用不同的方式回答，例如 \"We'd better visit him and bring some fruit.\" 或者分享另一个想法：\"I would send him a nice message to cheer him up.\""
            },
            {
                "content": "How do you help a classmate who finds homework difficult?",
                "ability": ["句型组织", "表达建议"],
                "explanation": "可以分享另一种帮助方式，比如 \"Let's give him a study plan so he can follow it step by step.\" 也可以说 \"We can study together after school.\""
            },
            {
                "content": "What do you hope for your best friend in the future?",
                "ability": ["句型组织", "表达愿望"],
                "explanation": "试着用不同的句型表达，例如 \"I hope he is able to follow his dream no matter what.\" 或者 \"I wish she will be happy and healthy forever.\""
            },
            {
                "content": "Tell us about a time when you helped someone else. How did you feel?",
                "ability": ["句型组织", "经历描述"],
                "explanation": "分享你帮助别人的经历，例如 \"I once helped a new classmate find her way around school. I felt proud because I made her feel welcome.\""
            },
            {
                "content": "Why is it important to help others in your class or family?",
                "ability": ["句型组织", "表达观点"],
                "explanation": "可以从更广的角度回答，例如 \"Helping others makes our class like a big family. When we help each other, nobody feels alone or sad.\""
            }
        ]
    }
}

SPEAKING_TOPIC_021801_TEXT1 = """【题目描述】
Look at these pictures about helping others. Talk about what you see and share your own ideas about helping and supporting friends.

【热词】
sick,classmate,help,homework,encourage,goal,dream,support,friend,teamwork

【图片描述】
Four images show children helping each other: 1st: A child brings a glass of water to a sick friend in bed. 2nd: Two children study together at a desk, one is explaining something. 3rd: A team of children celebrate together with hands raised. 4th: A child gives a present to a sad friend, who then smiles.

【题目】
1. What do you do when your friend is sick at home?
- 解析：可以用句型 "We'd better..." 来给出建议，例如 "We'd better call him and check how he feels." 也可以补充具体行动，如 "I would bring him homework and tell him to rest well."

2. How do you help a classmate who finds homework difficult?
- 解析：可以用 "Let's give him some tips so he can understand better." 来表达帮助方式。也可以说 "I explain the homework step by step and give examples."

3. What do you hope for your best friend in the future?
- 解析：可以用 "I hope he is able to achieve his goals." 来表达希望。也可以补充具体内容，如 "I hope she will go to a good school and make new friends."

4. Tell us about a time when someone helped you. How did it feel?
- 解析：用过去式描述一次被帮助的经历，例如 "Last term I couldn't do my maths homework. My friend sat with me after class and helped me finish it. I felt very warm and thankful."

5. Why is it important to help others in your class or family?
- 解析：可以从合作和友谊角度回答，例如 "When we help each other, we grow together. Helping makes the team stronger and everyone feels happy.\""""

SPEAKING_TOPIC_021801_TEXT2 = """【题目描述】
Now look at these pictures again. Think more deeply about helping others and share a different example or experience.

【热词】
sick,classmate,help,homework,encourage,goal,dream,support,friend,teamwork

【图片描述】
Same images as above: children helping each other in different situations.

【题目】
1. What do you do when your friend is sick at home?
- 解析：也可以用不同的方式回答，例如 "We'd better visit him and bring some fruit." 或者分享另一个想法："I would send him a nice message to cheer him up."

2. How do you help a classmate who finds homework difficult?
- 解析：可以分享另一种帮助方式，比如 "Let's give him a study plan so he can follow it step by step." 也可以说 "We can study together after school."

3. What do you hope for your best friend in the future?
- 解析：试着用不同的句型表达，例如 "I hope he is able to follow his dream no matter what." 或者 "I wish she will be happy and healthy forever."

4. Tell us about a time when you helped someone else. How did you feel?
- 解析：分享你帮助别人的经历，例如 "I once helped a new classmate find her way around school. I felt proud because I made her feel welcome."

5. Why is it important to help others in your class or family?
- 解析：可以从更广的角度回答，例如 "Helping others makes our class like a big family. When we help each other, nobody feels alone or sad.\""""

# --- 口语-P1-日常回答 | 021901 | L2 B级 ---
SPEAKING_QA_021901_JSON = {
    "first": {
        "category": "speaking",
        "type": "speaking_qa",
        "asrPrompt": "subject,Maths,English,Art,prefer,reading,running,drawing,friend,kind,helpful,hobby,because,enjoy,difficult",
        "questionSetID": "021901",
        "textDesc": "请回答以下问题。用清晰、完整的英文语句进行回答，分享你的真实想法和经历。",
        "questionSet": [
            {
                "content": "What school subject do you like? Why?",
                "ability": ["表达喜好与理由"],
                "explanation": "你可以用 \"I like...\" 来回答，例如 \"I like English because it is interesting for me.\" 也可以换成 Maths、Art 或其他你喜欢的科目，并说明理由。"
            },
            {
                "content": "Is there a subject that is hard for you? Why?",
                "ability": ["表达喜好与理由"],
                "explanation": "你可以说 \"Maths is hard for me because I find the problems difficult.\" 用 \"but it is... for me\" 的句型来表达你的感受，同时解释原因。"
            },
            {
                "content": "What do you prefer to do after school?",
                "ability": ["表达喜好与理由"],
                "explanation": "用 \"I prefer... to...\" 来回答，例如 \"I prefer reading to watching TV because I enjoy stories.\" 也可以说跑步、画画或和朋友玩。"
            },
            {
                "content": "What do you do with your best friend after school?",
                "ability": ["基础信息表达｜个人信息问答"],
                "explanation": "你可以回答 \"I play with my best friend after school.\" 然后用 \"I... because I...\" 来补充原因，例如 \"I play football with him because I love sports.\""
            }
        ]
    },
    "second": {
        "category": "speaking",
        "type": "speaking_qa",
        "asrPrompt": "sport,swimming,football,weekend,museum,park,movie,cooking,pizza,dumplings,English,learn,songs,stories,fun,useful",
        "questionSetID": "021901",
        "textDesc": "请回答以下问题。用清晰、完整的英文语句进行回答，分享你的真实想法和经历。",
        "questionSet": [
            {
                "content": "Do you like playing sports? Which sport do you like?",
                "ability": ["表达喜好与理由"],
                "explanation": "你可以用 \"I like... but it is... for me\" 来表达，例如 \"I like swimming, but it is tiring for me sometimes.\" 也可以换成 football、basketball 或 running。"
            },
            {
                "content": "What do you prefer to do on weekends?",
                "ability": ["表达喜好与理由"],
                "explanation": "用 \"I prefer... to...\" 来回答，例如 \"I prefer going to the park to staying at home.\" 也可以提到去博物馆、看电影或和朋友出去玩。"
            },
            {
                "content": "What food do you like but find hard to make?",
                "ability": ["表达喜好与理由"],
                "explanation": "试着说出一种你爱吃但不会做的食物，例如 \"I like dumplings, but they are hard for me to make alone.\" 也可以用 \"I... because I...\" 解释难度在哪儿。"
            },
            {
                "content": "Why do you enjoy learning English?",
                "ability": ["表达喜好与理由"],
                "explanation": "用 \"I enjoy learning English because I...\" 来表达，例如 \"I enjoy learning English because I can sing English songs and read interesting stories.\" 也可以说对将来有用或很有趣。"
            }
        ]
    }
}

SPEAKING_QA_021901_TEXT1 = """【题目描述】
请回答以下问题。用清晰、完整的英文语句进行回答，分享你的真实想法和经历。

【热词】
subject,Maths,English,Art,prefer,reading,running,drawing,friend,kind,helpful,hobby,because,enjoy,difficult

【题目】
1. What school subject do you like? Why?
- 解析：你可以用 "I like..." 来回答，例如 "I like English because it is interesting for me." 也可以换成 Maths、Art 或其他你喜欢的科目，并说明理由。

2. Is there a subject that is hard for you? Why?
- 解析：你可以说 "Maths is hard for me because I find the problems difficult." 用 "but it is... for me" 的句型来表达你的感受，同时解释原因。

3. What do you prefer to do after school?
- 解析：用 "I prefer... to..." 来回答，例如 "I prefer reading to watching TV because I enjoy stories." 也可以说跑步、画画或和朋友玩。

4. What do you do with your best friend after school?
- 解析：你可以回答 "I play with my best friend after school." 然后用 "I... because I..." 来补充原因，例如 "I play football with him because I love sports.\""""

SPEAKING_QA_021901_TEXT2 = """【题目描述】
请回答以下问题。用清晰、完整的英文语句进行回答，分享你的真实想法和经历。

【热词】
sport,swimming,football,weekend,museum,park,movie,cooking,pizza,dumplings,English,learn,songs,stories

【题目】
1. Do you like playing sports? Which sport do you like?
- 解析：你可以用 "I like... but it is... for me" 来表达，例如 "I like swimming, but it is tiring for me sometimes." 也可以换成 football、basketball 或 running。

2. What do you prefer to do on weekends?
- 解析：用 "I prefer... to..." 来回答，例如 "I prefer going to the park to staying at home." 也可以提到去博物馆、看电影或和朋友出去玩。

3. What food do you like but find hard to make?
- 解析：试着说出一种你爱吃但不会做的食物，例如 "I like dumplings, but they are hard for me to make alone." 也可以用 "I... because I..." 解释难度在哪儿。

4. Why do you enjoy learning English?
- 解析：用 "I enjoy learning English because I..." 来表达，例如 "I enjoy learning English because I can sing English songs and read interesting stories." 也可以说对将来有用或很有趣。"""

# --- 口语-P2-话题讨论 | 022001 | L2 B级 ---
SPEAKING_TOPIC_022001_JSON = {
    "first": {
        "category": "speaking",
        "type": "speaking_topic",
        "asrPrompt": "worried,afraid,dark,teach,brave,proud,challenge,climb,race,stop,fight,problem,difficult,solve",
        "questionSetID": "022001",
        "textDesc": "Look at these pictures about facing challenges and emotions. "
                    "Talk about what you see and share your own experiences with feelings and growth.",
        "imageDesc": "Four images show children dealing with different emotions and challenges: 1st: A child looks worried while staring at a big maths test paper. 2nd: A parent or teacher gently puts a hand on a child's shoulder, teaching them something. 3rd: A child stands on top of a small hill, arms raised with a proud smile. 4th: An adult stops a child from touching a hot kettle, pointing at it with a warning look.",
        "textImage": "022001-00.png",
        "questionSet": [
            {
                "content": "Have you ever seen a friend who looked worried? What happened?",
                "ability": ["句型组织", "经历描述"],
                "explanation": "描述一次观察到朋友担忧的经历，例如 \"My friend Tom is a happy boy, but he looked very worried before the maths test. I asked him what was wrong and he said he didn't study enough.\""
            },
            {
                "content": "Who taught you not to be afraid of something? What did they say?",
                "ability": ["句型组织", "经历描述"],
                "explanation": "回答谁教过你勇敢，例如 \"My mum taught me not to be afraid of the dark. She said there is nothing that can hurt me and that being brave makes you stronger.\""
            },
            {
                "content": "Tell us about a time you felt proud of yourself. What did you do?",
                "ability": ["句型组织", "经历描述"],
                "explanation": "用过去式描述一次自豪的经历，例如 \"I felt very proud when I finished a difficult race. I wanted to give up, but I kept running and reached the end.\""
            },
            {
                "content": "Has a parent or teacher ever stopped you from doing something? Why?",
                "ability": ["句型组织", "经历描述"],
                "explanation": "描述一次被阻止的经历，例如 \"My dad stopped me from climbing a tall tree. He said it was too dangerous and I could fall and get hurt.\""
            },
            {
                "content": "If you find anything really difficult, what will you do?",
                "ability": ["句型组织", "表达观点"],
                "explanation": "分享你面对困难的方法，例如 \"If I find anything difficult, I will ask my teacher or my parents for help. I will keep trying and not give up easily.\""
            }
        ]
    },
    "second": {
        "category": "speaking",
        "type": "speaking_topic",
        "asrPrompt": "worried,afraid,dark,teach,brave,proud,challenge,climb,race,stop,fight,problem,difficult,solve",
        "questionSetID": "022001",
        "textDesc": "Now look at these pictures again. Think about different experiences "
                    "and share another story about feelings, challenges or growing up.",
        "imageDesc": "Same images as above: children dealing with different emotions and challenges.",
        "textImage": "022001-01.png",
        "questionSet": [
            {
                "content": "Have you ever seen a friend who looked worried? What did you do to help?",
                "ability": ["句型组织", "经历描述"],
                "explanation": "分享你帮助朋友的经历，例如 \"Yes, my friend Lily looked sad after losing her favourite pen. I helped her search everywhere, and she smiled when we finally found it.\""
            },
            {
                "content": "Who taught you not to be afraid of trying new things? How did they help?",
                "ability": ["句型组织", "经历描述"],
                "explanation": "描述学习勇敢的过程，例如 \"My dad taught me not to be afraid of swimming. He held my hand in the water and slowly let go when I was ready.\""
            },
            {
                "content": "Tell us about a time you overcame a difficulty. How did you feel?",
                "ability": ["句型组织", "经历描述"],
                "explanation": "分享克服困难的经历，例如 \"I couldn't ride a bike at first. I kept falling, but I practised every day. I felt amazing when I finally rode without help.\""
            },
            {
                "content": "Why do parents or teachers sometimes stop children from doing things?",
                "ability": ["句型组织", "表达观点"],
                "explanation": "从理解的角度回答，例如 \"They stop us from doing dangerous things because they want to keep us safe. It is a way of showing their love and care.\""
            },
            {
                "content": "If you find anything difficult, what will you tell yourself?",
                "ability": ["句型组织", "表达观点"],
                "explanation": "分享你鼓励自己的话，例如 \"I will tell myself 'Never give up!' I believe that if I keep trying, I will find a way to solve the problem and become stronger.\""
            }
        ]
    }
}

SPEAKING_TOPIC_022001_TEXT1 = """【题目描述】
Look at these pictures about facing challenges and emotions. Talk about what you see and share your own experiences with feelings and growth.

【热词】
worried,afraid,dark,teach,brave,proud,challenge,climb,race,stop,fight,problem,difficult,solve

【图片描述】
Four images show children dealing with different emotions and challenges: 1st: A child looks worried while staring at a big maths test paper. 2nd: A parent or teacher gently puts a hand on a child's shoulder, teaching them something. 3rd: A child stands on top of a small hill, arms raised with a proud smile. 4th: An adult stops a child from touching a hot kettle, pointing at it with a warning look.

【题目】
1. Have you ever seen a friend who looked worried? What happened?
- 解析：描述一次观察到朋友担忧的经历，例如 "My friend Tom is a happy boy, but he looked very worried before the maths test. I asked him what was wrong and he said he didn't study enough."

2. Who taught you not to be afraid of something? What did they say?
- 解析：回答谁教过你勇敢，例如 "My mum taught me not to be afraid of the dark. She said there is nothing that can hurt me and that being brave makes you stronger."

3. Tell us about a time you felt proud of yourself. What did you do?
- 解析：用过去式描述一次自豪的经历，例如 "I felt very proud when I finished a difficult race. I wanted to give up, but I kept running and reached the end."

4. Has a parent or teacher ever stopped you from doing something? Why?
- 解析：描述一次被阻止的经历，例如 "My dad stopped me from climbing a tall tree. He said it was too dangerous and I could fall and get hurt."

5. If you find anything really difficult, what will you do?
- 解析：分享你面对困难的方法，例如 "If I find anything difficult, I will ask my teacher or my parents for help. I will keep trying and not give up easily.\""""

SPEAKING_TOPIC_022001_TEXT2 = """【题目描述】
Now look at these pictures again. Think about different experiences and share another story about feelings, challenges or growing up.

【热词】
worried,afraid,dark,teach,brave,proud,challenge,climb,race,stop,fight,problem,difficult,solve

【图片描述】
Same images as above: children dealing with different emotions and challenges.

【题目】
1. Have you ever seen a friend who looked worried? What did you do to help?
- 解析：分享你帮助朋友的经历，例如 "Yes, my friend Lily looked sad after losing her favourite pen. I helped her search everywhere, and she smiled when we finally found it."

2. Who taught you not to be afraid of trying new things? How did they help?
- 解析：描述学习勇敢的过程，例如 "My dad taught me not to be afraid of swimming. He held my hand in the water and slowly let go when I was ready."

3. Tell us about a time you overcame a difficulty. How did you feel?
- 解析：分享克服困难的经历，例如 "I couldn't ride a bike at first. I kept falling, but I practised every day. I felt amazing when I finally rode without help."

4. Why do parents or teachers sometimes stop children from doing things?
- 解析：从理解的角度回答，例如 "They stop us from doing dangerous things because they want to keep us safe. It is a way of showing their love and care."

5. If you find anything difficult, what will you tell yourself?
- 解析：分享你鼓励自己的话，例如 "I will tell myself 'Never give up!' I believe that if I keep trying, I will find a way to solve the problem and become stronger.\""""

# ============================================================
# API helpers
# ============================================================
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"]

def create_record(token, table_id, fields):
    r = requests.post(
        f"{BASE}/apps/{APP_TOKEN}/tables/{table_id}/records",
        headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
        json={"fields": fields}, timeout=15)
    return r.json()

# ============================================================
# Records to create
# ============================================================
records_to_create = [
    # (table_name, table_id, 题目集合 ID, jsonData, 题目1, 题目2)
    ("写作-P1-邮件回复", "tblszuk1TeToofBF", "021801",
     WRITING_021801_JSON, WRITING_021801_TEXT1, ""),
    ("写作-P1-邮件回复", "tblszuk1TeToofBF", "021901",
     WRITING_021901_JSON, WRITING_021901_TEXT1, ""),
    ("写作-P1-邮件回复", "tblszuk1TeToofBF", "022001",
     WRITING_022001_JSON, WRITING_022001_TEXT1, ""),
    ("口语-P2-话题讨论", "tblGoWYBmVI0IrvQ", "021801",
     SPEAKING_TOPIC_021801_JSON, SPEAKING_TOPIC_021801_TEXT1, SPEAKING_TOPIC_021801_TEXT2),
    ("口语-P1-日常回答", "tblRGv7k4WH58Jgq", "021901",
     SPEAKING_QA_021901_JSON, SPEAKING_QA_021901_TEXT1, SPEAKING_QA_021901_TEXT2),
    ("口语-P2-话题讨论", "tblGoWYBmVI0IrvQ", "022001",
     SPEAKING_TOPIC_022001_JSON, SPEAKING_TOPIC_022001_TEXT1, SPEAKING_TOPIC_022001_TEXT2),
]

def main():
    token = get_token()
    print("Token OK")
    
    for i, (tname, tid, qsid, jd, t1, t2) in enumerate(records_to_create):
        fields = {
            "题目集合 ID": qsid,
            "dataStatus": "0",
            "jsonData": json.dumps(jd, ensure_ascii=False),
            "题目1": t1,
        }
        if t2:
            fields["题目2"] = t2
        # 口语-P1 has 题目1热词 and 题目2热词
        if tname == "口语-P1-日常回答":
            fields["题目1热词"] = "subject,Maths,English,Art,prefer,reading,running,drawing,friend,kind,helpful,hobby"
            fields["题目2热词"] = "sport,swimming,football,weekend,museum,park,movie,cooking"
        
        result = create_record(token, tid, fields)
        code = result.get("code")
        if code == 0:
            rid = result.get("data",{}).get("record",{}).get("record_id","?")
            print(f"[{i+1}/6] ✅ {tname} QSID={qsid} → {rid}")
        else:
            print(f"[{i+1}/6] ❌ {tname} QSID={qsid} FAIL: {result.get('msg')}")
    
    print("\nDone!")

if __name__ == "__main__":
    main()
