#!/usr/bin/env python3
"""reading_pic_qa 010701 + 010801, L2 A级"""
import json, requests, time

CRED = "/root/.openclaw/credentials/xiaoyan/config.json"
TOKEN = "CMHSbUUjka3TrUsaxxEc297ongf"
TBL = "tblweY65jGBiwSdt"

with open(CRED) as f:
    cred = json.load(f)
aid = cred["apps"][0]["appId"]
asecret = cred["apps"][0]["appSecret"]

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

token = get_token()

DATA = {
    "010701": {
        "first": [
            ("A notebook is on the desk.", "Yes", "桌子上放着一本打开的笔记本，句子描述正确。"),
            ("A star is on the wall.", "Yes", "墙上贴着一颗黄色的星星贴纸，句子描述正确。"),
            ("A folder is under the chair.", "No", "文件夹在桌上，不在椅子下面，句子与图片不匹配。"),
            ("The girl reads a diary.", "Yes", "女孩坐在桌前翻开一本日记在阅读，句子描述正确。"),
            ("The contact list is on the wall.", "No", "联系人列表在电脑屏幕上，不在墙上贴着，句子与图片不匹配。"),
        ],
        "second": [
            ("A friendly girl gives you a flower.", "Yes", "一个面带微笑的女孩伸手递出一朵花，她很友好，句子描述正确。"),
            ("A crazy boy is jumping on the desk.", "No", "男孩安静地坐在桌前看书，没有在桌上跳，他不疯狂，句子与图片不匹配。"),
            ("A brilliant student has a gold star.", "Yes", "一个学生拿着A+试卷，上面贴着金色星星，她非常优秀，句子描述正确。"),
            ("A kind boy helps his friend.", "Yes", "一个男孩蹲下帮另一个孩子捡起掉在地上的书，他很善良，句子描述正确。"),
            ("The little girl is afraid of the dog.", "No", "小女孩开心地摸着小狗的头，她并不害怕，句子与图片不匹配。"),
        ],
    },
    "010801": {
        "first": [
            ("Uncle is reading a newspaper.", "Yes", "叔叔坐在沙发上展开一份报纸在读，句子描述正确。"),
            ("Aunt is cooking in the kitchen.", "No", "阿姨坐在沙发上织毛衣，不在厨房做饭，句子与图片不匹配。"),
            ("Grandma is sitting in an armchair.", "Yes", "奶奶坐在一张扶手椅上，腿上盖着毯子，句子描述正确。"),
            ("The neighbour is at the door.", "No", "门口没有邻居，只有一只宠物狗趴在地板上，句子与图片不匹配。"),
            ("A pet dog is sleeping on the floor.", "Yes", "一只宠物狗趴在客厅地板上闭着眼睛睡觉，句子描述正确。"),
        ],
        "second": [
            ("The house looks expensive.", "Yes", "房子外观很大气，花园整洁，有雕花栏杆，看起来很贵，句子描述正确。"),
            ("A boy is at the entrance.", "Yes", "男孩站在房子大门口（入口处），正按门铃，句子描述正确。"),
            ("A cat is walking upstairs.", "No", "小猫正在沿着楼梯往下走（downstairs），不是往上走（upstairs），句子与图片不匹配。"),
            ("A girl is running downstairs.", "Yes", "一个女孩正从楼梯上跑下来，头发飘起，句子描述正确。"),
            ("Mum is making toast in the kitchen.", "No", "妈妈在客厅窗边看书，不在厨房做吐司，句子与图片不匹配。"),
        ],
    },
}

TT = "Look and read. Put a tick (Yes) or a cross (No) in the box."
AB = ["图文判断", "句图一致性"]

def build(qid, grp_name, questions):
    return {
        "category": "reading",
        "type": "reading_pic_qa",
        "questionSetID": qid,
        "textTitle": TT,
        "textImage": f"{qid}-{'00' if grp_name=='first' else '01'}.png",
        "questionSet": [
            {"question": q, "answerText": a, "ability": AB, "explanation": x}
            for q, a, x in questions
        ],
    }

def build_full(qid):
    return {
        "first": build(qid, "first", DATA[qid]["first"]),
        "second": build(qid, "second", DATA[qid]["second"]),
    }

# Delete existing
print("=== Clean ===")
resp = requests.get(f"https://open.feishu.cn/open-apis/bitable/v1/apps/{TOKEN}/tables/{TBL}/records?page_size=20",
                    headers={"Authorization": f"Bearer {token}"})
for item in resp.json()["data"]["items"]:
    fid = item["fields"].get("题目集合 ID", "")
    if fid in DATA:
        requests.delete(
            f"https://open.feishu.cn/open-apis/bitable/v1/apps/{TOKEN}/tables/{TBL}/records/{item['record_id']}",
            headers={"Authorization": f"Bearer {token}"})
        print(f"  Deleted {fid}")

time.sleep(2)

# Create empty
print("\n=== Create ===")
rids = {}
for qid in sorted(DATA):
    r = requests.post(f"https://open.feishu.cn/open-apis/bitable/v1/apps/{TOKEN}/tables/{TBL}/records",
                      headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
                      json={"fields": {"题目集合 ID": qid, "dataStatus": "0"}})
    rid = r.json()["data"]["record"]["record_id"]
    rids[qid] = rid
    print(f"  {qid}: {rid}")
    time.sleep(0.5)

# Wait for automation
print("\n=== Wait 30s ===")
time.sleep(30)

# Update with jsonData
print("\n=== Update ===")
token = get_token()
for qid in sorted(rids):
    j = build_full(qid)
    js = json.dumps(j, ensure_ascii=False)
    fy = sum(1 for q in j["first"]["questionSet"] if q["answerText"] == "Yes")
    fn = 5 - fy
    print(f"  {qid}: first={fy}Y/{fn}N, json={len(js)}chars")
    r = requests.put(f"https://open.feishu.cn/open-apis/bitable/v1/apps/{TOKEN}/tables/{TBL}/records/{rids[qid]}",
                     headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
                     json={"fields": {"jsonData": js}})
    print(f"    update code={r.json().get('code')}")
    time.sleep(0.5)

# Wait & verify
print("\n=== Wait 30s ===")
time.sleep(30)

token = get_token()
print("\n=== Verify ===")
for qid in sorted(rids):
    r = requests.get(f"https://open.feishu.cn/open-apis/bitable/v1/apps/{TOKEN}/tables/{TBL}/records/{rids[qid]}",
                     headers={"Authorization": f"Bearer {token}"})
    jd = r.json()["data"]["record"]["fields"].get("jsonData", "")
    try:
        j = json.loads(jd)
        fq = len(j["first"]["questionSet"])
        sq = len(j["second"]["questionSet"])
        q1 = j["first"]["questionSet"][0]["question"][:50]
        print(f"  {'✅' if fq==5 and sq==5 else '❌'} {qid}: {fq}/{sq}q Q1='{q1}'")
    except Exception as e:
        print(f"  ❌ {qid}: {e}")
print("Done.")
