"""
qnaigc 专用 LLM 客户端
模型：arcee-ai/trinity-large-preview
"""

import requests
import json
from typing import Optional

class LLMError(Exception):
    pass

CONFIG = {
    "base_url": "https://api.qnaigc.com/v1",
    "api_key": "sk-2cb9561a18351015d3120ffac4abae0480fa17e0d28469bdce5fc905d1a42e0d",
    "model": "arcee-ai/trinity-large-preview",
}

def call_llm(
    prompt: str,
    system_prompt: str = "你是一个专业的内容创作助手。",
    temperature: float = 0.7,
    max_tokens: int = 2000,
    stream: bool = False,
) -> str:
    endpoint = f"{CONFIG['base_url'].rstrip('/')}/chat/completions"
    headers = {
        "Authorization": f"Bearer {CONFIG['api_key']}",
        "Content-Type": "application/json"
    }
    payload = {
        "model": CONFIG["model"],
        "messages": [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": prompt}
        ],
        "temperature": temperature,
        "max_tokens": max_tokens,
        "stream": stream,
    }
    try:
        resp = requests.post(endpoint, json=payload, headers=headers, timeout=120, stream=stream)
        if resp.status_code != 200:
            raise LLMError(f"HTTP {resp.status_code}: {resp.text[:200]}")
        if stream:
            full = []
            for line in resp.iter_lines():
                if not line:
                    continue
                if line.startswith(b'data: '):
                    data = line[6:]
                    if data == b'[DONE]':
                        break
                    try:
                        chunk = json.loads(data)
                        delta = chunk['choices'][0]['delta']
                        if 'reasoning_content' in delta and delta['reasoning_content']:
                            full.append(delta['reasoning_content'])
                        if 'content' in delta and delta['content']:
                            full.append(delta['content'])
                    except Exception:
                        continue
            return "".join(full)
        else:
            data = resp.json()
            msg = data["choices"][0]["message"]
            content = msg.get('content') or msg.get('reasoning') or msg.get('reasoning_content')
            return content.strip() if content else ''
    except requests.RequestException as e:
        raise LLMError(f"Request failed: {e}")

def expand_content_with_llm(topic: dict, section_title: str, section_content: str, context: str = "") -> str:
    """扩写大纲章节，返回包含 ## 标题的完整 Markdown"""
    prompt = f"""你是一个专业的内容创作者，风格精炼、直接、切中要点。请将以下大纲扩展为完整的文章章节，要求如下：

### 选题信息
标题：{topic.get('title')}
领域：{topic.get('field')}
核心观点：{topic.get('core_concept', '')}
受众痛点：{topic.get('audience_pain', '')}
独特视角：{topic.get('unique_angle', '')}

### 当前章节
## {section_title}
{section_content}

### 输出要求
- 以 "## {section_title}" 开始
- 字数：200-300 字（精炼为主）
- 语言：直白、有冲击力，避免空洞套话
- 使用 Markdown 格式
- 每个论点配具体案例或数据支撑
- 确保与整体文章调性一致

直接输出完整 Markdown 章节（包括标题和正文）。"""
    if context:
        prompt = f"# 参考资料\n{context}\n\n{prompt}"

    try:
        result = call_llm(prompt, temperature=0.8, max_tokens=1000)
        return result.strip()
    except Exception as e:
        return f"## {section_title}\n\n（LLM 调用失败：{e}，请手动补充）"

# 测试
if __name__ == "__main__":
    try:
        print(f"[qnaigc_client] 使用模型: {CONFIG['model']}")
        resp = call_llm("你好，请用一句话介绍你自己。", max_tokens=50)
        print(f"[qnaigc_client] 响应: {resp}")
    except Exception as e:
        print(f"[qnaigc_client] 错误: {e}")
