#!/usr/bin/env python3
"""Fix ability / abilityTag to match standard 45 tags."""
import subprocess, json

APP_TOKEN = "CMHSbUUjka3TrUsaxxEc297ongf"
TABLE_ID = "tblszuk1TeToofBF"
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"]

# Standard 45 tags for writing P1 email:
# 7. 短消息写作｜邮件/便条
# 8. 衔接与连贯｜连词使用
# 9. 描述写作｜人物/物体/场景
CORE_TAGS = ["短消息写作｜邮件/便条", "衔接与连贯｜连词使用"]
DESC_TAG = "描述写作｜人物/物体/场景"

RECORDS = {
    "recvjzbkvoOgvy": {"qid": "022201", "desc": False},   # box - no description
    "recvjzblhhNt7Q": {"qid": "022301", "desc": True},    # garden - describes garden
    "recvjzblXOJ7Fs": {"qid": "022401", "desc": True},    # hospital - describes Jack
    "recvjzXjMKAQ4i": {"qid": "032501", "desc": False},   # encouragement
    "recvjzXklYIE05": {"qid": "032601", "desc": False},   # thank you
    "recvjzXkYnsQ8r": {"qid": "032701", "desc": True},    # cafe - describes cafe/people
    "recvjzXlxz4r3i": {"qid": "032801", "desc": False},   # problem solving
    "recvjzXm5yEXBY": {"qid": "032901", "desc": True},    # party - describes party/people
}

for rid, spec in RECORDS.items():
    qid = spec["qid"]
    tags = CORE_TAGS + ([DESC_TAG] if spec["desc"] else [])
    
    url = f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE_ID}/records/{rid}"
    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'])
    
    jd['first']['ability'] = tags
    jd['first']['abilityTag'] = tags
    
    body = json.dumps({"fields": {"jsonData": json.dumps(jd, ensure_ascii=False)}}, 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)
    
    # 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'])
    a = jd2['first']['ability']
    at = jd2['first']['abilityTag']
    ok = a == tags and at == tags
    print(f"[{qid}] ability={a} abilityTag={at} {'✅' if ok else '❌'}")
