"""
Backfill 10 unit challenge records to Feishu bitable
Reads from /tmp/unit_challenge_records.json
"""
import json, urllib.request

APP_TOKEN = "CMHSbUUjka3TrUsaxxEc297ongf"
CRED_FILE = "/root/.openclaw/credentials/xiaoyan/config.json"

TABLES = {
    "writing_email": "tblszuk1TeToofBF",
    "writing_picWrite": "tblSAwlMumKoyjws",
    "speaking_qa": "tblRGv7k4WH58Jgq",
    "speaking_topic": "tblGoWYBmVI0IrvQ",
}

with open(CRED_FILE) as f:
    cfg = json.load(f)
req = urllib.request.Request(
    "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
    data=json.dumps({"app_id": cfg['apps'][0]['appId'], "app_secret": cfg['apps'][0]['appSecret']}).encode(),
    headers={"Content-Type": "application/json"})
token = json.loads(urllib.request.urlopen(req).read())['tenant_access_token']

def api(url, method='GET', body=None):
    h = {"Authorization": f"Bearer {token}"}
    d = json.dumps(body).encode() if body else None
    if d: h["Content-Type"] = "application/json"
    r = urllib.request.Request(url, data=d, method=method, headers=h)
    return json.loads(urllib.request.urlopen(r).read())

with open('/tmp/unit_challenge_records.json') as f:
    records = json.load(f)

ok = 0
fail = 0

for rec in records:
    tid = TABLES[rec['table']]
    sid = rec['sid']
    
    # Find existing record
    url = f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{tid}/records?page_size=100"
    resp = api(url)
    
    rid = None
    for item in resp['data']['items']:
        if item['fields'].get('题目集合 ID', '') == sid:
            rid = item['record_id']
            break
    
    new_jd = json.dumps(rec['json'], ensure_ascii=False)
    fields = {
        "题目集合 ID": sid,
        "jsonData": new_jd,
        "题目1": rec.get('t1', '')
    }
    
    if rid:
        result = api(
            f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{tid}/records/{rid}",
            'PUT', {"fields": fields}
        )
        st = "UPD" if result.get('code') == 0 else f"ERR:{result.get('msg')}"
    else:
        result = api(
            f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{tid}/records",
            'POST', {"fields": fields}
        )
        st = "NEW" if result.get('code') == 0 else f"ERR:{result.get('msg')}"
    
    if result.get('code') == 0:
        ok += 1
    else:
        fail += 1
    print(f"  {st} {rec['type']} {sid}")

print(f"\n✅ OK={ok} FAIL={fail}")
