from WebsiteSpider.settings import MAX_TEXT_LENGTH, TRANSLATE_API_URL, REQUEST_DELAY
import requests
import time
from typing import List, Tuple, Optional

def normalize_newlines(text: str) -> str:
    """将 \r\n 和 \r 统一转换为 \n"""
    if not text:
        return text
    return text.replace('\r\n', '\n').replace('\r', '\n')


def translate_single(text: str, source_lang: str = "auto", target_lang: str = "zh") -> Optional[str]:
    """翻译单段文本，失败返回 None"""
    if not text or not text.strip():
        return ""

    payload = {
        "text": text[:MAX_TEXT_LENGTH],
        "source_lang": source_lang,
        "target_lang": target_lang
    }

    try:
        response = requests.post(TRANSLATE_API_URL, json=payload, timeout=10)
        response.raise_for_status()
        result = response.json()
        return result.get("translated_text")
    except Exception as e:
        print(f"⚠️ 翻译失败: {e}")
        return None


def translate_content_with_paragraphs(content: str) -> str:
    """
    按段落翻译内容，支持容错：
    - 某段失败 → 跳过该段（保留空行或原文）
    - 返回拼接后的完整内容
    """
    if not content:
        return ""

    # 标准化换行符
    content = normalize_newlines(content)
    paragraphs = content.split('\n')
    translated_paragraphs = []

    for para in paragraphs:
        if not para.strip():
            # 保留空行
            translated_paragraphs.append("")
            continue

        trans = translate_single(para)
        if trans is None:
            # 段落翻译失败：跳过该段（可选：保留原文或留空）
            print(f"  ⚠️ 段落翻译失败，跳过: {para[:30]}...")
            translated_paragraphs.append("")  # 或 append(para) 保留原文
        else:
            translated_paragraphs.append(trans)

        time.sleep(REQUEST_DELAY)

    return '\n'.join(translated_paragraphs)


# ================== 数据库操作 ==================

def update_record(cursor, es_sid: int, new_title: str, new_content: str):
    update_query = """
        UPDATE indeximos 
        SET es_title = % s, es_content = % s 
        WHERE es_sid = % s
    """
    cursor.execute(update_query, (new_title, new_content, es_sid))
