#!/usr/bin/env python3
"""Create records first, then update jsonData separately."""
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"]

# First delete all corrupted records
print("=== Cleaning corrupted records ===")
resp = requests.get(
    f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE_ID}/records?page_size=20",
    headers={"Authorization": f"Bearer {token}"},
)
for item in resp.json()["data"]["items"]:
    fid = item["fields"].get("题目集合 ID", "")
    if fid in ("000001", "010101", "010201", "010301", "010401", "010501", "010601"):
        rid = item["record_id"]
        del_resp = requests.delete(
            f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE_ID}/records/{rid}",
            headers={"Authorization": f"Bearer {token}"},
        )
        print(f"  Deleted {fid} ({rid}): {del_resp.json().get('code')}")

time.sleep(2)

results = {}
for qid in sorted(ALL_QUESTIONS.keys()):
    print(f"\n{'='*50}")
    print(f"ID: {qid}")
    
    # Step 1: Create with minimal fields (no jsonData)
    fields = {
        "题目集合 ID": qid,
        "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')}")
        results[qid] = "FAIL_CREATE"
        continue
    
    record_id = result["data"]["record"]["record_id"]
    print(f"  Created: {record_id}")
    
    # Step 2: Update with jsonData
    json_data = build_json(qid, ALL_QUESTIONS[qid])
    json_str = json.dumps(json_data, ensure_ascii=False)
    print(f"  Updating jsonData ({len(json_str)} chars)...")
    
    update_resp = requests.put(
        f"https://open.feishu.cn/open-apis/bitable/v1/apps/{APP_TOKEN}/tables/{TABLE_ID}/records/{record_id}",
        headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
        json={"fields": {"jsonData": json_str}},
    )
    up_result = update_resp.json()
    print(f"  Update: code={up_result.get('code')}")
    
    if up_result.get("code") != 0:
        print(f"  ❌ Update failed: {up_result.get('msg')}")
        results[qid] = "FAIL_UPDATE"
        continue
    
    # Wait for any automation to process
    time.sleep(1.0)
    
    # Step 3: Read back and verify
    resp3 = 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}"},
    )
    data3 = resp3.json()
    stored_jd = data3["data"]["record"]["fields"].get("jsonData", "")
    
    try:
        j = json.loads(stored_jd)
        fq = len(j["first"]["questionSet"])
        sq = len(j["second"]["questionSet"])
        if fq == 5 and sq == 5:
            first_q = j["first"]["questionSet"][0]["question"][:50]
            print(f"  ✅ VERIFIED: first={fq}q, second={sq}q, Q1='{first_q}'")
            results[qid] = ("OK", record_id)
        else:
            print(f"  ⚠️ PARTIAL: first={fq}q, second={sq}q")
            results[qid] = ("PARTIAL", record_id)
    except Exception as e:
        print(f"  ❌ CORRUPTED: {e} | jd_len={len(stored_jd)}")
        results[qid] = ("CORRUPTED", record_id)
    
    time.sleep(1.0)

print(f"\n{'='*50}")
print("FINAL SUMMARY")
print(f"{'='*50}")
for qid, val in sorted(results.items()):
    print(f"  {qid}: {val}")
