#!/usr/bin/env python3
"""
S2 英文台词简化 + 飞书 Sheet 写回
- 简单台词（≤5词无从句）→ 直接复制到 F 列
- 复杂台词 → 直接 LLM 简化（保留原文语义），不走 gen_script 全流程
- 结果写回飞书 Sheet F 列
"""
import os, sys, json, time
from openai import OpenAI
import requests

# ============================================================
# 配置
# ============================================================
SPREADSHEET_TOKEN = "UK7ms9UrdhJllftVOaOc4r4envg"
SHEET_ID = "wMQVyV"
DIALOGUE_FILE = "/root/.openclaw/workspace-xiaoyan/business_production/英文台词/output/dialogue_lines_current.json"

# LLM client
client = OpenAI(
    api_key="32994652-505c-492b-b6da-616ec5c5733c",
    base_url="https://ark.cn-beijing.volces.com/api/v3"
)
LLM_MODEL = "ep-m-20260301164317-vmmj4"

# Feishu auth
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_fs_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"]

S2_SIMPLIFY_PROMPT = """You are adapting English children's dialogue for S2 level (5-6 year old beginners).

### CRITICAL RULES
1. **PRESERVE THE EXACT MEANING** — never change what the line communicates. Only simplify HOW it's said.
2. Keep sentences under 8 words each.
3. Use only simple present/past/future (will/be going to) — no perfect tense, no conditionals.
4. Replace difficult words with simpler ones a 5-6 year old would know.
5. Keep natural speaking rhythm — short bursts, child-friendly expressions.
6. Keep interjections (Oh!, Uh-oh, Yay!, Haha, Oops!) — they add emotion.
7. Keep character names and key nouns (Vala, astronaut, spaceship, etc.).
8. If the original line is already simple enough, KEEP IT UNCHANGED.

### Format
Input: "Character: English line"
Output: English line only — no character name, no explanation.

### Examples
Input: "Mum: I received a special delivery from Vala headquarters this morning."
Output: Look! A box came from Vala! It got here this morning.

Input: "User: I want to wear the astronaut uniform but it's too big for me."
Output: I want to wear this. But it's too big for me!

Input: "Dad: What are you doing with that paper and pencil?"
Output: What are you doing? What's that for?"""

def simplify_line(char, text, retries=2):
    """Simplify a single English line for S2 level"""
    prompt = f"{char}: {text}"
    
    for attempt in range(retries + 1):
        try:
            resp = client.chat.completions.create(
                model=LLM_MODEL,
                messages=[
                    {"role": "system", "content": S2_SIMPLIFY_PROMPT},
                    {"role": "user", "content": prompt}
                ],
                temperature=0.3,
                max_tokens=200,
                timeout=30,
                extra_body={"thinking": {"type": "disabled"}}
            )
            result = resp.choices[0].message.content.strip()
            # Clean up: remove character name prefix if present
            if ": " in result:
                parts = result.split(": ", 1)
                result = parts[1].strip() if len(parts) > 1 else result.strip()
            return result
        except Exception as e:
            if attempt < retries:
                time.sleep(2)
            else:
                raise e

def is_simple(text):
    """Check if a line is already S2-level simple"""
    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 m in clause_markers:
        if f" {m} " in f" {text_lower} " or text_lower.startswith(m + " "):
            return False
    return True

def write_to_sheet(token, row_num, text, col_idx=5):
    """Write to column F (index 5)"""
    col_letter = chr(65 + col_idx)
    range_str = f"{SHEET_ID}!{col_letter}{row_num + 1}:{col_letter}{row_num + 1}"
    payload = {"valueRange": {"range": range_str, "values": [[text]]}}
    resp = requests.put(
        f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{SPREADSHEET_TOKEN}/values",
        headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
        json=payload)
    return resp.json().get("code") == 0

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

token = get_fs_token()
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(text):
            english = text
            simple_count += 1
            print("→ SIMPLE (direct)")
        else:
            english = simplify_line(char, text)
            complex_count += 1
            print(f"→ S2: {english[:50]}...")
    except Exception as e:
        english = text  # fallback to original
        errors.append((row, str(e)))
        print(f"→ ERROR: {e}, fallback to original")
    
    if write_to_sheet(token, row, english):
        print(f"  ✅ F{row+1}")
    else:
        print(f"  ❌ Write failed")
        errors.append((row, "Write failed"))
    
    time.sleep(0.3)

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