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}")

# Prepare the updates. 
# Feishu API uses A1 notation. 
# Row indices in our csv are 1-based but let's double check.
# The CSV had line 1 as headers: 类型,None,None,剧情描述,角色名,编剧台词,None,None
# Let's read the exact row indices from the CSV we generated to map exactly.
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 # 1-based
    return -1

r6 = find_row_by_text(5, "You can borrow any book you like from there.")
r7 = find_row_by_text(5, "Wow, that sounds like a wonderful place!")
r92 = find_row_by_text(5, "Stories and videos live inside.")
r94 = find_row_by_text(5, "Inside this?")
r207 = find_row_by_text(5, "You can find e-books and DVDs.")
r208 = find_row_by_text(5, "Let us write it together.")

r143 = find_row_by_text(5, "The drawing is about a boy with big dreams.")
r144 = find_row_by_text(5, "I guess... this is a book about adventure.")

print("Found rows:", r6, r7, r92, r94, r207, r208, r143, r144)

if r6 != -1: update_cell(f"G{r6}:G{r6}", [["【知识点修改】为了覆盖句型 '... can... at the library.' (要求IN≥2)，建议改为 'You can read books at the library.' (IN 1)"]])
if r7 != -1: update_cell(f"G{r7}:G{r7}", [["【知识点补充】建议在此处下方增加一个中互动，User: 'We can read books at the library.' (OUT 1)"]])
if r92 != -1: update_cell(f"G{r92}:G{r92}", [["【知识点修改】建议改为句型输入：'You can watch DVDs at the library.' (IN 2)"]])
if r94 != -1: update_cell(f"G{r94}:G{r94}", [["【知识点补充】建议在此处下方增加一个中互动，User: 'We can watch DVDs at the library.' (OUT 2)"]])
if r207 != -1: update_cell(f"G{r207}:G{r207}", [["【知识点修改】为了铺垫第3次OUT，建议改为 'You can find e-books and DVDs at the library.' (IN 3)"]])
if r208 != -1: update_cell(f"G{r208}:G{r208}", [["【知识点补充】建议在此处下方增加一个中互动，User: 'We can find e-books at the library.' (OUT 3) 作为该句型的最后一次输出。"]])

if r143 != -1: update_cell(f"G{r143}:G{r143}", [["【知识点修改】为了补充 'This is a book about...' 的 IN 2，建议改为 'This is a book about a boy with big dreams.'"]])
if r144 != -1: update_cell(f"G{r144}:G{r144}", [["【批注】此处应明确标记为中互动，作为 'This is a book about...' 的第3次OUT。"]])

# Add ending. Find the last line.
last_line_idx = find_row_by_text(5, "Even online, it should stay open.")
if last_line_idx != -1:
    new_rows = [
        ["中互动", "", "", "", "User", "The paper books have our memories."],
        ["", "", "", "", "Sue", "And the e-books will make new memories!"],
        ["", "", "", "", "Bingo", "Stories always live forever!"]
    ]
    start_row = last_line_idx + 1
    end_row = last_line_idx + 3
    update_cell(f"A{start_row}:F{end_row}", new_rows)

