#!/usr/bin/env python3
"""
Fix component production issues:
1. Regenerate 4 对话朗读 rows with correct format (no 组件ID, correct 资源配置)
2. Fix Chinese error feedback → English for 7 other rows
"""
import requests, json, time, os

CRED_PATH = "/root/.openclaw/credentials/xiaoyan/config.json"
SHEET_TOKEN = "VgPwsodzthsk9Vti8GocrbH2nEe"
SHEET_ID = "wMQVyV"
OUTPUT_DIR = "/root/.openclaw/workspace-xiaoyan/business_production/组件生产/output"

LLM_BASE = "https://ark.cn-beijing.volces.com/api/v3"
LLM_KEY = "32994652-505c-492b-b6da-616ec5c5733c"
LLM_MODEL = "ep-m-20260301164317-vmmj4"

def get_token():
    with open(CRED_PATH) as f: c = json.load(f)
    r = requests.post("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
        json={"app_id": c["apps"][0]["appId"], "app_secret": c["apps"][0]["appSecret"]})
    return r.json()["tenant_access_token"]

def get_sheet(token):
    r = requests.get(
        f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{SHEET_TOKEN}/values/{SHEET_ID}?majorDimension=ROWS",
        headers={"Authorization": f"Bearer {token}"})
    return r.json()["data"]["valueRange"]["values"]

def write_cell(token, sheet_row, content):
    range_str = f"{SHEET_ID}!H{sheet_row}:H{sheet_row}"
    r = requests.put(
        f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{SHEET_TOKEN}/values",
        headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
        json={"valueRange": {"range": range_str, "values": [[content]]}})
    return r.json().get("code") == 0

def parse_col(row, idx):
    if isinstance(row[idx], list):
        return "".join([seg.get("text","") for seg in row[idx] if isinstance(seg, dict)])
    return str(row[idx]) if row[idx] else ""

def llm(messages):
    try: from openai import OpenAI
    except: os.system("pip install openai --break-system-packages -q"); from openai import OpenAI
    client = OpenAI(base_url=LLM_BASE, api_key=LLM_KEY)
    resp = client.chat.completions.create(
        model=LLM_MODEL, messages=messages, temperature=0.3, max_tokens=1000,
        extra_body={"thinking": {"type": "disabled"}})
    return resp.choices[0].message.content.strip()

# === FIX: 对话朗读 regeneration ===
READING_SYSTEM = """You fix dialogue reading component configs.

## CORRECT FORMAT (exactly this, no variation):

【任务标题】{contextual title fitting the scene, ≤10 chars}
【资源配置】
图片时机：
情境引入
互动内容
互动反馈
【情境引入】
{Character: line, or 无 if no context needed}
【互动内容】
{Character}: {sentence}（朗读）
【后置对话】
{Character: next line from context, or 无}

## KEY RULES
- NO 【组件ID】 field at all!
- NO 音频载体 line!
- NO 【互动反馈】 section!
- 资源配置 uses line-break stage listing format (情境引入/互动内容/互动反馈 on separate lines)
- Task title must match the scene context, not generic like "朗读台词" 
- Error feedback (互动反馈) appears only as a stage name in 资源配置, NOT as a separate section
- Generate only the component config text, no explanation"""

def fix_reading(token, row_data):
    """Regenerate a 对话朗读 component"""
    messages = [
        {"role": "system", "content": READING_SYSTEM},
        {"role": "user", "content": f"""Fix this 对话朗读 component:

Context:
- Scene: {row_data.get('plot','')}
- Knowledge Point: {row_data.get('kp','')}

Dialogue before:
{row_data.get('ctx_before','')}

Current interaction:
{row_data.get('char','User')}: {row_data.get('script_en','')}

Dialogue after:
{row_data.get('ctx_after','')}

Generate the corrected component config following the format exactly. Make the task title contextual and scene-fitting."""}
    ]
    return llm(messages)

# === FIX: Chinese error feedback → English ===
FB_SYSTEM = """You fix Chinese error feedback in English learning component configs.
Replace Chinese feedback text with natural English character dialogue that matches the scene context and character personality.
Keep everything else exactly the same. Only change the error feedback text.

Format: return the complete fixed component config text, changing ONLY the error feedback lines."""

def fix_feedback(token, old_content, context):
    """Fix Chinese error feedback"""
    messages = [
        {"role": "system", "content": FB_SYSTEM},
        {"role": "user", "content": f"""Fix the Chinese error feedback in this component config:

Component context: {context}

Current config:
{old_content}

Return the complete fixed config with Chinese feedback replaced by natural English character dialogue."""}
    ]
    return llm(messages)

def main():
    token = get_token()
    values = get_sheet(token)
    os.makedirs(OUTPUT_DIR, exist_ok=True)
    
    # Collect context for all rows
    rows = []
    for i, row in enumerate(values):
        while len(row) < 8: row.append(None)
        rtype = str(row[0]).strip() if row[0] else ""
        rows.append({
            "sheet_row": i+1, "type": rtype,
            "id": str(row[1]).strip() if row[1] else "",
            "plot": str(row[2]).strip() if row[2] else "",
            "char": str(row[3]).strip() if row[3] else "",
            "script_cn": parse_col(row, 4), "script_en": parse_col(row, 5),
            "kp": str(row[6]).strip() if row[6] else "",
            "h_col": str(row[7]) if row[7] else "",
        })
    
    # Find dialogue reading rows and other fixable rows
    reading_rows = []
    cn_feedback_rows = []
    
    for i, r in enumerate(rows):
        if r["type"] == "对话朗读" and r["h_col"]:
            # Get context
            ctx_before = []
            for j in range(max(0,i-4), i):
                if rows[j]["char"] and rows[j]["script_cn"]:
                    ctx_before.append(f"{rows[j]['char']}: {rows[j]['script_cn']}")
            ctx_after = []
            for j in range(i+1, min(len(rows), i+4)):
                if rows[j]["char"] and rows[j]["script_cn"]:
                    ctx_after.append(f"{rows[j]['char']}: {rows[j]['script_cn']}")
            r["ctx_before"] = "\n".join(ctx_before)
            r["ctx_after"] = "\n".join(ctx_after)
            reading_rows.append(r)
        
        elif r["h_col"]:
            # Check for Chinese error feedback
            err_idx = r["h_col"].find("错误：")
            if err_idx > 0:
                err_line = r["h_col"][err_idx:].split("\n")[0]
                has_cn = any('\u4e00' <= c <= '\u9fff' for c in err_line)
                # Skip section headers (正确/错误) - only check after "错误：" before newline
                fb_text = err_line.split("错误：")[1] if "错误：" in err_line else err_line
                if any('\u4e00' <= c <= '\u9fff' for c in fb_text):
                    cn_feedback_rows.append(r)
    
    print(f"对话朗读 to fix: {len(reading_rows)}")
    print(f"中文反馈 to fix: {len(cn_feedback_rows)}")
    
    results = []
    
    # Fix dialogue readings
    for r in reading_rows:
        row_num = r["sheet_row"]
        print(f"\n[对话朗读] Row {row_num} ID={r['id']}")
        try:
            new_content = fix_reading(token, r)
            print(f"  Generated: {new_content[:100]}...")
            if write_cell(token, row_num, new_content):
                print(f"  ✅ Written to H{row_num}")
                results.append({"row": row_num, "type": "对话朗读", "status": "fixed"})
            else:
                print(f"  ❌ Write failed")
                results.append({"row": row_num, "type": "对话朗读", "status": "write_fail"})
        except Exception as e:
            print(f"  ❌ Error: {e}")
            results.append({"row": row_num, "type": "对话朗读", "status": str(e)})
        time.sleep(0.5)
    
    # Fix Chinese feedback
    for r in cn_feedback_rows:
        row_num = r["sheet_row"]
        rtype = r["type"]
        print(f"\n[{rtype}] Row {row_num} ID={r['id']} — fixing Chinese feedback")
        ctx = f"Character: {r['char']}, Plot: {r['plot']}, KP: {r['kp']}"
        try:
            new_content = fix_feedback(token, r["h_col"], ctx)
            if write_cell(token, row_num, new_content):
                print(f"  ✅ Written")
                results.append({"row": row_num, "type": rtype, "status": "fb_fixed"})
            else:
                print(f"  ❌ Write failed")
        except Exception as e:
            print(f"  ❌ Error: {e}")
        time.sleep(0.5)
    
    # Summary
    ok = sum(1 for r in results if "fail" not in r["status"] and "Error" not in str(r["status"]))
    print(f"\n{'='*40}")
    print(f"Fixed: {ok}/{len(results)}")
    for r in results:
        print(f"  H{r['row']} [{r['type']}]: {r['status']}")

if __name__ == "__main__":
    main()
