import json, requests, time

conf = json.load(open('/root/.openclaw/credentials/xiaoxi/config.json'))
app = conf['apps'][0]

# Get tenant access token
r = requests.post("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal", json={
    "app_id": app['appId'],
    "app_secret": app['appSecret']
})
token = r.json()['tenant_access_token']
print(f"Token obtained: {token[:20]}...")

headers = {
    "Authorization": f"Bearer {token}",
    "Content-Type": "application/json"
}

# For now, just test if we can write a simple block to the data dictionary doc
doc_id = "YEk6dWmsHoT02lxlO3tcNBrHnXe"

# First, get the document to see its current state
r = requests.get(f"https://open.feishu.cn/open-apis/docx/v1/documents/{doc_id}", headers=headers)
print(f"Get doc: {r.json().get('code')} - {r.json().get('msg','')}")

# Try to create a block
block_data = {
    "document_id": doc_id,
    "blocks": [
        {
            "block_type": 2,  # text block
            "text": {
                "elements": [
                    {"text_run": {"content": "Hello from API test"}}
                ],
                "style": {}
            }
        }
    ]
}

r = requests.post(
    f"https://open.feishu.cn/open-apis/docx/v1/documents/{doc_id}/blocks",
    headers=headers,
    json=block_data
)
print(f"Create blocks: code={r.json().get('code')}, msg={r.json().get('msg','')}")
print(json.dumps(r.json(), indent=2, ensure_ascii=False)[:500])
