#!/usr/bin/env python3
"""Create ONE reading_pic_qa record with immediate verification."""
import json, requests, sys

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

qid = "000001"
json_data = build_json(qid, ALL_QUESTIONS[qid])
json_str = json.dumps(json_data, ensure_ascii=False)
print(f"jsonData size: {len(json_str)} chars")

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"]

# Create record
fields = {
    "题目集合 ID": qid,
    "jsonData": json_str,
    "dataStatus": "0",
}

print(f"\n=== Creating record ===")
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()
print(f"Create response code: {result.get('code')}")

if result.get("code") != 0:
    print(f"ERROR: {result}")
    sys.exit(1)

record_id = result["data"]["record"]["record_id"]
print(f"record_id: {record_id}")

# Read back immediately
print(f"\n=== Reading back ===")
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", "")
print(f"Stored jsonData size: {len(stored_jd)} chars")

if len(stored_jd) < 100:
    print(f"TRUNCATED! Content: {repr(stored_jd)}")
    # Delete it
    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}"},
    )
else:
    # Verify content
    try:
        j = json.loads(stored_jd)
        fq = len(j["first"]["questionSet"])
        sq = len(j["second"]["questionSet"])
        print(f"✅ OK: first={fq} questions, second={sq} questions")
    except Exception as e:
        print(f"Parse error: {e}")
        print(f"First 200 chars: {stored_jd[:200]}")
