"""
回填听力审校结果到飞书多维表格
"""
import json, urllib.request, sys

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

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

def backfill(record_id, table_id, audit_text):
    token = get_token()
    body = json.dumps({"fields": {"审校结果": audit_text}}).encode()
    url = f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{table_id}/records/{record_id}"
    req = urllib.request.Request(url, data=body, method="PUT", headers={
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    })
    resp = json.loads(urllib.request.urlopen(req).read())
    return resp.get('code') == 0, resp

# Load audit results
with open("/tmp/listening_audit_results.json") as f:
    results = json.load(f)

print(f"Total records to backfill: {len(results)}")
success = 0
failed = []

for r in results:
    ok, resp = backfill(r['record_id'], r['table_id'], r['audit_text'])
    if ok:
        success += 1
        status = "✅" if "通过" in r['audit_text'].split('\n')[0] else "📝"
        print(f"{status} {r['table_name']:10s} | ID={r['sid']:10s} | OK")
    else:
        failed.append(r)
        print(f"❌ {r['table_name']:10s} | ID={r['sid']:10s} | FAIL: {resp}")

print(f"\n===== 回填完成 =====")
print(f"成功: {success}/{len(results)}")
if failed:
    print(f"失败: {len(failed)}")
    for f in failed:
        print(f"  {f['table_name']} ID={f['sid']}")
