#!/usr/bin/env python3
"""Fix 4 problematic writing records: 032701, 032901, 022101, 032801"""
import requests, json, time

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

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()

# Fetch current records that need fixing
targets = {
    "032701": "recvjzXkYnsQ8r",
    "032901": "recvjzXm5yEXBY",
    "022101": "recvjzbjJpJO0D",
    "032801": "recvjzXlxz4r3i",
}

fixes = {}

for qsid, rid in targets.items():
    r = requests.get(
        f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE}/records/{rid}",
        headers={"Authorization": f"Bearer {token}"}, timeout=10)
    jd_str = r.json()["data"]["record"]["fields"]["jsonData"]
    jd = json.loads(jd_str)
    fixes[qsid] = {"rid": rid, "jd": jd}
    time.sleep(0.2)

# ============= PATCH 032701 =============
fixes["032701"]["jd"]["first"]["answerSet"] = [0, 1, 2, 3, 4, 5, 6, 7]
fixes["032701"]["jd"]["first"]["ability"] = [
    "短消息写作｜邮件/便条",
    "衔接与连贯｜连词使用",
    "描述性写作｜人物与地点"
]
fixes["032701"]["jd"]["first"]["explanation"] = (
    "按描述邮件的逻辑：称呼→描述人物→外貌对比→地点氛围→澄清发现者→补充人名→补充地点→署名。"
    "考察They are/looks different from/a place that/it is not...who/someone named/too...to...等句型。"
    "C级体现：多句型切换和描述性词汇的运用，需理解人物描写→地点过渡→细节补充的自然衔接。"
)

# ============= PATCH 032901 =============
fixes["032901"]["jd"]["first"]["answerSet"] = [0, 1, 2, 3, 4, 5, 6, 7]
fixes["032901"]["jd"]["first"]["ability"] = [
    "短消息写作｜邮件/便条",
    "衔接与连贯｜连词使用",
    "描述性写作｜场景与情绪"
]
fixes["032901"]["jd"]["first"]["explanation"] = (
    "按聚会描述的逻辑：称呼→妹妹的动态→毫不在意→妈妈的心情→自己的限制→爸爸的状态→大家的穿着→署名。"
    "考察loves to/doesn't care/will be so happy that/can't...because/seems in a...mood/is wearing等句型。"
    "C级体现：多人物平行描述和情感状态的切换，需要理解热闹场景下的视线焦点转移。"
)

# ============= PATCH 022101 =============
fixes["022101"]["jd"]["first"]["answerSet"] = [0, 1, 2, 3, 4, 5, 6]
if "ability" not in fixes["022101"]["jd"]["first"] or not fixes["022101"]["jd"]["first"]["ability"]:
    fixes["022101"]["jd"]["first"]["ability"] = [
        "短消息写作｜邮件/便条",
        "衔接与连贯｜连词使用"
    ]
# Check if ability is ['句型组织'] (wrong for writing)
if fixes["022101"]["jd"]["first"]["ability"] == ["句型组织"]:
    fixes["022101"]["jd"]["first"]["ability"] = [
        "短消息写作｜邮件/便条",
        "衔接与连贯｜连词使用"
    ]

# ============= PATCH 032801 =============
fixes["032801"]["jd"]["first"]["answerSet"] = [0, 1, 2, 3, 4, 5, 6]
if fixes["032801"]["jd"]["first"]["ability"] == ["句型组织"]:
    fixes["032801"]["jd"]["first"]["ability"] = [
        "短消息写作｜邮件/便条",
        "衔接与连贯｜连词使用",
        "问题解决｜求助与建议"
    ]

# Write back all fixes
for qsid in ["032701", "032901", "022101", "032801"]:
    data = fixes[qsid]
    rid = data["rid"]
    jd = data["jd"]
    new_jd_str = json.dumps(jd, ensure_ascii=False)
    
    r = requests.put(
        f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE}/records/{rid}",
        headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
        json={"fields": {"jsonData": new_jd_str}}, timeout=15)
    code = r.json().get("code")
    if code == 0:
        print(f"[✅] {qsid} 修复成功")
    else:
        print(f"[❌] {qsid}: {r.json().get('msg')}")
    time.sleep(0.3)

# Verify
print("\n=== 验证 ===")
for qsid in ["032701", "032901", "022101", "032801"]:
    rid = targets[qsid]
    r = requests.get(
        f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE}/records/{rid}",
        headers={"Authorization": f"Bearer {token}"}, timeout=10)
    jd = json.loads(r.json()["data"]["record"]["fields"]["jsonData"])
    first = jd["first"]
    ans = first["answerSet"]
    ab = first["ability"]
    expl = first.get("explanation", "")
    opt = first.get("optionSetList", [])
    
    issues = []
    if len(ans) != len(opt):
        issues.append(f"🔴 ans({len(ans)})≠opt({len(opt)})")
    if not ab:
        issues.append("🔴 ability为空")
    if len(expl) < 20:
        issues.append(f"🔴 expl过短({len(expl)}字)")
    
    status = "✅" if not issues else " ".join(issues)
    print(f"  {qsid}: {status} | ans={ans} | ab={ab}")
    time.sleep(0.2)

print("\n全部修复完成。")
