#!/usr/bin/env python3
"""Batch create reading_pic_qa records with delay and immediate verification."""
import json, requests, sys, time

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

sys.path.insert(0, '/root/.openclaw/workspace-xiaoyan')
from scripts.batch_reading_pic_qa import ALL_QUESTIONS, build_json

with open(CRED_FILE) as f:
    cred = json.load(f)
app_id = cred["apps"][0]["appId"]
app_secret = cred["apps"][0]["appSecret"]

token_resp = requests.post(
    "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
    json={"app_id": app_id, "app_secret": app_secret},
)
token = token_resp.json()["tenant_access_token"]

results = []
for qid in sorted(ALL_QUESTIONS.keys()):
    print(f"\n{'='*50}")
    print(f"ID: {qid}")
    
    json_data = build_json(qid, ALL_QUESTIONS[qid])
    json_str = json.dumps(json_data, ensure_ascii=False)
    print(f"  jsonData: {len(json_str)} chars")
    
    # Verify Y/N balance
    for grp in ('first', 'second'):
        qs = json_data[grp]['questionSet']
        yc = sum(1 for q in qs if q['answerText']=='Yes')
        nc = sum(1 for q in qs if q['answerText']=='No')
        print(f"  {grp}: {yc}Y/{nc}N")
    
    # Create
    fields = {
        "题目集合 ID": qid,
        "jsonData": json_str,
        "dataStatus": "0",
    }
    resp = requests.post(
        f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE_ID}/records",
        headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
        json={"fields": fields},
    )
    result = resp.json()
    
    if result.get("code") != 0:
        print(f"  ❌ Create failed: {result.get('msg', result)}")
        results.append((qid, "FAIL"))
        continue
    
    record_id = result["data"]["record"]["record_id"]
    print(f"  record_id: {record_id}")
    
    # Verify immediately
    time.sleep(0.5)
    resp2 = requests.get(
        f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE_ID}/records/{record_id}",
        headers={"Authorization": f"Bearer {token}"},
    )
    data2 = resp2.json()
    stored_jd = data2["data"]["record"]["fields"].get("jsonData", "")
    
    if len(stored_jd) < 100:
        print(f"  ❌ TRUNCATED ({len(stored_jd)} chars)! Deleting...")
        requests.delete(
            f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE_ID}/records/{record_id}",
            headers={"Authorization": f"Bearer {token}"},
        )
        results.append((qid, "TRUNCATED"))
        continue
    
    try:
        j = json.loads(stored_jd)
        fq = len(j["first"]["questionSet"])
        sq = len(j["second"]["questionSet"])
        print(f"  ✅ Verified: first={fq}q, second={sq}q")
        results.append((qid, "OK", record_id))
    except Exception as e:
        print(f"  ❌ Parse error: {e}")
        results.append((qid, "PARSE_ERROR"))
    
    time.sleep(1.0)

print(f"\n{'='*50}")
print("SUMMARY")
print(f"{'='*50}")
for r in results:
    print(f"  {r}")
