import json
import urllib.request
import sys
import subprocess

# get token
cmd = "APP_ID=$(jq -r '.apps[0].appId' /root/.openclaw/credentials/xiaobian/config.json) && APP_SECRET=$(jq -r '.apps[0].appSecret' /root/.openclaw/credentials/xiaobian/config.json) && curl -s -X POST 'https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal' -H 'Content-Type: application/json' -d \"{\\\"app_id\\\":\\\"$APP_ID\\\",\\\"app_secret\\\":\\\"$APP_SECRET\\\"}\" | jq -r '.tenant_access_token'"
token = subprocess.check_output(cmd, shell=True, text=True).strip()

spreadsheet_token = "KnTpsmp0XhYyXutZdxgcPFubnjh"
sheet_id = "eQUhYO"

url = f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{spreadsheet_token}/values/{sheet_id}!A1:H210"
req = urllib.request.Request(url)
req.add_header("Authorization", f"Bearer {token}")
req.add_header("Content-Type", "application/json")

try:
    response = urllib.request.urlopen(req)
    data = json.loads(response.read().decode('utf-8'))
    values = data.get('data', {}).get('valueRange', {}).get('values', [])
    
    # Let's print the last 15 rows to see the ending transition
    last_rows = values[-20:]
    for i, row in enumerate(values):
        # We extract speaker and dialog text
        if len(row) > 5:
            speaker = row[4]
            dialog = row[5]
            if speaker or dialog:
                pass # Just ensuring we don't print everything, maybe just the end.

    print("--- Last 15 rows ---")
    for i in range(max(0, len(values)-15), len(values)):
        row = values[i]
        speaker = row[4] if len(row) > 4 else ""
        dialog = row[5] if len(row) > 5 else ""
        if isinstance(dialog, list):
             dialog = "".join([c.get('text', '') if isinstance(c, dict) else str(c) for c in dialog])
        if isinstance(speaker, list):
             speaker = "".join([c.get('text', '') if isinstance(c, dict) else str(c) for c in speaker])
        print(f"Row {i+1}: [{speaker}] {dialog}")
except Exception as e:
    print(f"Error fetching: {e}")
