"""教师原创请求例。默认只检查请求，不联网；--live 才发一次请求。Python 3.9+，仅标准库。"""
import argparse
import json
import os
import urllib.error
import urllib.request

ENDPOINT = 'https://api.deepseek.com/chat/completions'

def build_request(model, question):
    if not model.strip() or not question.strip():
        raise ValueError('模型名称和问题均不能为空')
    return {'model': model, 'messages': [
        {'role': 'system', 'content': '仅根据用户给定材料回答；缺失信息写未提供。'},
        {'role': 'user', 'content': question}], 'stream': False, 'max_tokens': 512}

def parse_response(data):
    if not isinstance(data, dict):
        raise ValueError('响应必须是JSON对象')
    choices = data.get('choices')
    if not isinstance(choices, list) or not choices:
        raise ValueError('响应缺少 choices，请检查当期接口说明与错误信息')
    first = choices[0]
    if not isinstance(first, dict) or not isinstance(first.get('message'), dict):
        raise ValueError('响应缺少有效message对象')
    text = first['message'].get('content')
    if not isinstance(text, str) or not text.strip():
        raise ValueError('未得到最终文字；检查输出上限、响应状态或模型模式')
    return {'answer': text, 'usage': data.get('usage'), 'finish_reason': first.get('finish_reason')}

def send(payload, key):
    if not key:
        raise ValueError('未配置 DEEPSEEK_API_KEY；没有发送请求')
    req = urllib.request.Request(ENDPOINT, data=json.dumps(payload).encode('utf-8'),
        headers={'Authorization': 'Bearer ' + key, 'Content-Type': 'application/json'})
    with urllib.request.urlopen(req, timeout=45) as response:
        return parse_response(json.load(response))

def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--model', required=True, help='从当期官方模型列表核对名称；不自动选型')
    p.add_argument('--question', default='原创样例：周三15:00在图书馆二楼举行资料分享，报名方式未提供。请提取时间、地点、报名方式。')
    p.add_argument('--live', action='store_true')
    a = p.parse_args(); payload = build_request(a.model, a.question)
    if not a.live:
        print(json.dumps({'mode': 'dry_run_no_network', 'endpoint': ENDPOINT, 'payload': payload}, ensure_ascii=False, indent=2)); return
    try:
        result = send(payload, os.environ.get('DEEPSEEK_API_KEY', ''))
        print(json.dumps({'mode': 'live_api', **result}, ensure_ascii=False, indent=2))
    except urllib.error.HTTPError as error:
        print(json.dumps({'mode': 'live_failed', 'http_status': error.code, 'message': '请求失败。核对官方错误码、账户和限额；本例不自动重试，不打印密钥或完整响应。'}, ensure_ascii=False))
        raise SystemExit(1)
    except (urllib.error.URLError, ValueError, TimeoutError) as error:
        print(json.dumps({'mode': 'failed', 'error_type': type(error).__name__, 'message': str(error)}, ensure_ascii=False)); raise SystemExit(1)

if __name__ == '__main__': main()
