#!/usr/bin/env python3
"""
批量英文台词生产 + 飞书 Sheet 写回脚本
- 简单台词（≤5词，无从句）直接复制到 F 列
- 复杂台词通过 gen_script.py pipeline 处理
- 结果写回飞书嵌入式 Sheet 的 F 列（英文台词）
"""
import os, sys, json, time, requests

# ============================================================
# 配置
# ============================================================
SPREADSHEET_TOKEN = "VgPwsodzthsk9Vti8GocrbH2nEe"
SHEET_ID = "wMQVyV"
STAGE = "S2"
DIALOGUE_FILE = "/root/.openclaw/workspace-xiaoyan/business_production/英文台词/output/dialogue_lines.json"

# OpenAI 配置
os.environ["OPENAI_API_KEY"] = "32994652-505c-492b-b6da-616ec5c5733c"
os.environ["OPENAI_BASE_URL"] = "https://ark.cn-beijing.volces.com/api/v3"
os.environ["OPENAI_MODEL"] = "ep-m-20260301164317-vmmj4"

# ============================================================
# 飞书凭证
# ============================================================
with open("/root/.openclaw/credentials/xiaoyan/config.json") as f:
    cred = json.load(f)
APP_ID = cred["apps"][0]["appId"]
APP_SECRET = cred["apps"][0]["appSecret"]

def get_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})
    return resp.json()["tenant_access_token"]

TOKEN = get_token()
HEADERS = {"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"}

# ============================================================
# Import gen_script functions
# ============================================================
sys.path.insert(0, "/root/.openclaw/workspace-xiaoyan/business_production/英文台词/skills/kids-english-script-production/scripts")
from gen_script import generate_single_script, call_llm

def is_simple_line(text):
    """判断台词是否已经是 S2 级别简单句"""
    words = text.split()
    if len(words) > 5:
        return False
    clause_markers = ['because', 'which', 'that', 'when', 'if', 'after',
                      'before', 'while', 'although', 'since', 'until',
                      'unless', 'where', 'who', 'whom', 'whose']
    text_lower = text.lower()
    for marker in clause_markers:
        if f" {marker} " in f" {text_lower} " or text_lower.startswith(marker + " "):
            return False
    return True

def write_to_sheet(row_num, text, col_index=5):
    """Write text to a specific cell in the sheet"""
    # Column F = index 5 (0-based)
    col_letter = chr(65 + col_index)  # A=0, B=1, ..., F=5
    cell = f"{col_letter}{row_num + 1}"
    range_str = f"{SHEET_ID}!{cell}:{cell}"
    
    payload = {
        "valueRange": {
            "range": range_str,
            "values": [[text]]
        }
    }
    resp = requests.put(
        f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{SPREADSHEET_TOKEN}/values",
        headers=HEADERS,
        json=payload)
    return resp.json().get("code") == 0

# ============================================================
# Main
# ============================================================
with open(DIALOGUE_FILE, "r", encoding="utf-8") as f:
    items = json.load(f)

simple_count = 0
complex_count = 0
errors = []

for idx, item in enumerate(items):
    row = item["row"]
    char = item["char"]
    text = item["text"]
    
    print(f"[{idx+1}/{len(items)}] Row {row}: {char}: {text[:60]}...", end=" ", flush=True)
    
    try:
        if is_simple_line(text):
            # Simple line - copy directly
            english = text
            simple_count += 1
            print(f"→ SIMPLE (direct copy)")
        else:
            # Complex line - process through pipeline
            complex_count += 1
            input_text = f"{char}: {text}"
            result = generate_single_script(input_text, STAGE, verbose=False)
            
            # Extract clean English from pipeline result
            result_str = str(result)
            # Remove trace report
            trace_marker = "\n" + "=" * 60 + "\n📋"
            if trace_marker in result_str:
                result_str = result_str[:result_str.index(trace_marker)].strip()
            # Remove stage header
            lines = result_str.split("\n")
            if lines and lines[0].startswith("【"):
                lines = lines[1:]
            # Extract the English text after "角色: "
            english_lines = []
            for line in lines:
                line = line.strip()
                if line and ": " in line:
                    # Format: "角色: English text"
                    parts = line.split(": ", 1)
                    if len(parts) == 2:
                        english_lines.append(parts[1].strip())
            english = " ".join(english_lines) if english_lines else text
            print(f"→ COMPLEX (pipeline: {english[:50]}...)")
    except Exception as e:
        # On any error, fallback to original text
        english = text
        errors.append((row, str(e)))
        print(f"→ ERROR: {e}, using original")
    
    # Write to sheet
    if write_to_sheet(row, english):
        print(f"  ✅ Written to F{row+1}")
    else:
        print(f"  ❌ Write failed for row {row}")
        errors.append((row, "Write failed"))
    
    # Rate limit
    time.sleep(0.3)

# Summary
print(f"\n{'='*60}")
print(f"DONE: {simple_count} simple (direct copy) + {complex_count} pipeline processed")
print(f"Total: {len(items)}, Errors: {len(errors)}")
if errors:
    print("Errors:")
    for r, e in errors:
        print(f"  Row {r}: {e}")
