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"

def update_cell(range_str, values):
    url = f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{spreadsheet_token}/values"
    req = urllib.request.Request(url, method="PUT")
    req.add_header("Authorization", f"Bearer {token}")
    req.add_header("Content-Type", "application/json")
    data = {"valueRange": {"range": f"{sheet_id}!{range_str}", "values": values}}
    try:
        response = urllib.request.urlopen(req, data=json.dumps(data).encode('utf-8'))
        print(f"Updated {range_str}: {response.read().decode('utf-8')}")
    except Exception as e:
        print(f"Error updating {range_str}: {e}")

import csv
csv_lines = []
with open('output/u27_5_sheet.csv', 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        csv_lines.append(row)

def find_row_by_text(col_idx, text):
    for i, row in enumerate(csv_lines):
        if len(row) > col_idx and text in row[col_idx]:
            return i + 1
    return -1

# Fix 1: folders
r76 = find_row_by_text(5, "We need to put them in the right folder.")
if r76 != -1: update_cell(f"F{r76}:G{r76}", [["We need to put them in the right folders.", "【语法修改】folder应为复数 folders"]])

# Fix 2: folder says
r87 = find_row_by_text(5, "So it goes into the folder says")
if r87 != -1: update_cell(f"F{r87}:G{r87}", [["So it goes into the \"animals\" folder.", "【语法修改】原句 'folder says' 缺少从句引导词，改为更口语的 the 'animals' folder"]])

# Fix 3: haven't copy
r120 = find_row_by_text(5, "We haven't copy it.")
if r120 != -1: update_cell(f"F{r120}:G{r120}", [["We didn't copy it yet.", "【语法修改】haven't 后面应跟 copied，为了儿童阅读更简单，改为 didn't copy it yet."]])

# Fix Ending
r223 = find_row_by_text(5, "Even online, it should stay open.")
if r223 != -1:
    # We will replace Lily's line and append the 3 lines smoothly
    new_rows = [
        ["", "", "", "", "Lily", "I will show Mayor Tom his old book!"],
        ["", "", "", "", "Lily", "Maybe the paper library should stay open too!"],
        ["中互动", "", "", "", "User", "Yes! The paper books keep our memories."],
        ["", "", "", "", "Sue", "And the e-books share them with everyone!"],
        ["", "", "", "", "Bingo", "So the stories live forever!"]
    ]
    # We'll overwrite starting from r223
    update_cell(f"A{r223}:F{r223+4}", new_rows)

