#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""调用 DeepSeek-V4-Pro(官方) 或 SCNetX(Auto) 做审核，输出最终文本到文件。"""
import sys, json, re, pathlib, urllib.request

CRED = pathlib.Path.home() / '.dsh' / '.credentials.yaml'
def key(name):
    t = CRED.read_text(encoding='utf-8')
    m = re.search(rf'^\s*{name}:\s*"?([^"\n]+)"?', t, re.M)
    return m.group(1).strip() if m else ''

def main():
    provider, prompt_file, out_file = sys.argv[1], sys.argv[2], sys.argv[3]
    prompt = pathlib.Path(prompt_file).read_text(encoding='utf-8')
    if provider == 'deepseek':
        url = 'https://api.deepseek.com/v1/chat/completions'
        model = 'deepseek-v4-pro'
        api_key = key('DEEPSEEK_API_KEY')
    elif provider == 'deepseek-or':
        # DeepSeek-V4-Pro 经 OpenRouter 托管（官方 API 余额不足时的等效通道，同一模型）
        url = 'https://openrouter.ai/api/v1/chat/completions'
        model = 'deepseek/deepseek-v4-pro'
        api_key = key('OPENROUTER_API_KEY')
    elif provider == 'scnetx':
        url = 'https://api.scnet.cn/api/llm/v1/chat/completions'
        model = 'Auto'
        api_key = key('SCNET_API_KEY')
    elif provider == 'scnet-pro':
        # DeepSeek-V4-Pro 经 SCNet 托管（OpenRouter 通道不可用时的等效替代，同一模型）
        url = 'https://api.scnet.cn/api/llm/v1/chat/completions'
        model = 'DeepSeek-V4-Pro-0813'
        api_key = key('SCNET_API_KEY')
    elif provider == 'scnet-flash':
        # SCNet 侧稳定通道：DeepSeek-V4.1-Flash-1017，显式关思考（Auto 在长提示下会超时）
        url = 'https://api.scnet.cn/api/llm/v1/chat/completions'
        model = 'DeepSeek-V4.1-Flash-1017'
        api_key = key('SCNET_API_KEY')
    else:
        raise SystemExit('unknown provider')
    payload = {
        'model': model,
        'messages': [{'role': 'user', 'content': prompt}],
        'max_tokens': 24000,
        'reasoning_effort': 'low',
        'reasoning': {'enabled': False},
        'stream': False,
    }
    if provider.startswith('scnet'):
        payload.pop('reasoning_effort', None)
        payload.pop('reasoning', None)
        payload['thinking'] = {'type': 'disabled'}
    req = urllib.request.Request(url, data=json.dumps(payload).encode('utf-8'),
        headers={'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json'})
    with urllib.request.urlopen(req, timeout=900) as r:
        data = json.loads(r.read().decode('utf-8'))
    msg = data.get('choices', [{}])[0].get('message', {})
    content = (msg.get('content') or '').strip()
    reasoning = (msg.get('reasoning_content') or '').strip()
    used = data.get('model', model)
    body = content if content else reasoning
    if not body:
        body = json.dumps(data, ensure_ascii=False)
    out = pathlib.Path(out_file)
    out.write_text(f"[provider={provider}] [model={used}]\n\n{body}\n", encoding='utf-8')
    print(f"wrote {out} ({len(body)} chars, model={used})")

if __name__ == '__main__':
    main()
