#!/usr/bin/env python3
"""Fix 3 records with wrong answerSet ordering."""
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)
TOKEN = json.loads(r.stdout)["tenant_access_token"]

def get_jsonData(rid):
    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)
    f = json.loads(r.stdout)['data']['record']['fields']
    return json.loads(f['jsonData'])

def set_jsonData(rid, jd):
    url = f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE_ID}/records/{rid}"
    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)
    resp = json.loads(r.stdout)
    return resp.get("code") == 0

fixes = [
    ("recvjzbkvoOgvy", "022201", [0, 2, 3, 5, 1, 4]),
    ("recvjzblhhNt7Q", "022301", [1, 4, 5, 2, 0, 3]),
    ("recvjzXlxz4r3i", "032801", [5, 0, 4, 2, 1, 3]),
]

for rid, qid, correct_ans in fixes:
    print(f"[{qid}] Fixing answerSet to {correct_ans}...", end=" ")
    jd = get_jsonData(rid)
    jd['first']['answerSet'] = correct_ans
    ok = set_jsonData(rid, jd)
    
    # Verify
    jd2 = get_jsonData(rid)
    stored = jd2['first']['answerSet']
    if stored == correct_ans:
        print("✅ Fixed")
    else:
        print(f"❌ Still wrong: got {stored}")
