"""Fox API 首次文本调用。用 Python 3 在自己的终端运行，无需安装第三方包。"""
import getpass
import json
from urllib.error import HTTPError, URLError
from urllib.request import HTTPRedirectHandler, Request, build_opener

BASE = 'https://foxapi.xin/v1'  # 本例使用本站标准文本入口


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, *args):
        return None  # 不把密钥带到重定向地址


def request(path, headers, body=None):
    payload = json.dumps(body).encode() if body is not None else None
    req = Request(BASE + path, data=payload, headers=headers)
    with build_opener(NoRedirect).open(req, timeout=90) as res:
        return json.load(res)


def main():
    protocol = input('按分组说明输入协议 chat / responses / messages：').strip().lower()
    if protocol not in ('chat', 'responses', 'messages'):
        return '未选择支持的协议，没有发送请求。'
    key = getpass.getpass('粘贴本站密钥，再按回车（不会回显）：').strip()
    if not key:
        return '没有输入密钥。'
    headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + key}
    if protocol == 'messages':
        headers = {'Content-Type': 'application/json', 'x-api-key': key, 'anthropic-version': '2023-06-01'}
    catalog = request('/models', headers)
    ids = [row['id'] for row in catalog.get('data', []) if row.get('id')]
    if not ids:
        return '目录为空。先核对密钥分组，不要尝试随机模型名。'
    print('此密钥可见的模型：', *ids, sep='\n')
    model = input('从上述列表复制一个支持该协议的文本模型 ID：').strip()
    if model not in ids:
        return '模型不在列表中，没有发送生成请求。'
    if input('下一步会按正常用量计费。只发一次？输入 y 确认：').strip().lower() != 'y':
        return '已停止，只查询了目录。'
    prompt = '只回复：你好'
    body = {'model': model, 'messages': [{'role': 'user', 'content': prompt}]}
    path = '/chat/completions'
    if protocol == 'responses':
        path, body = '/responses', {'model': model, 'input': prompt}
    elif protocol == 'messages':
        path, body['max_tokens'] = '/messages', 64
    result = request(path, headers, body)
    if result.get('error') or result.get('status') in ('failed', 'incomplete', 'cancelled', 'in_progress', 'queued'):
        detail = result.get('error') or result.get('incomplete_details') or {}
        hint = (detail.get('code') or detail.get('type') or detail.get('reason') or '') if isinstance(detail, dict) else ''
        return f'收到 HTTP 成功响应，但任务未确认完成：{result.get("status", "error")} {hint}。先核对使用记录，不自动重发。'
    if protocol == 'chat':
        text = next((c.get('message', {}).get('content') for c in result.get('choices', []) if c.get('message', {}).get('content')), '')
    elif protocol == 'responses':
        text = ''.join(c.get('text', '') for item in result.get('output', []) for c in item.get('content', []) if c.get('type') == 'output_text')
    else:
        text = ''.join(c.get('text', '') for c in result.get('content', []) if c.get('type') == 'text')
    return ('回复：' + text if isinstance(text, str) and text.strip() else '收到响应但没有可读正文。') + '\n请到「使用记录」核对本次调用。'


if __name__ == '__main__':
    try:
        print(main())
    except HTTPError as err:
        print('HTTP', err.code, '；请求标识：', err.headers.get('x-request-id') or err.headers.get('request-id', '未提供'))
        if err.headers.get('Retry-After'):
            print('Retry-After：', err.headers['Retry-After'], '（秒数或日期；不要早于它重试）')
        try:
            detail = json.loads(err.read(8192))
            if isinstance(detail, dict):
                error = detail.get('error', detail)
                if isinstance(error, dict):
                    print(error.get('code') or error.get('type') or '', error.get('status') or '', str(error.get('message') or detail.get('message', ''))[:240])
                else:
                    print(detail.get('code', ''), detail.get('message', ''))
        except (ValueError, UnicodeError):
            print('这次没有可解析的 JSON 错误；若看到网页、跳转或 CDN 错误，按手册的地址或网络条目查。')
        print('对照手册的「按报错找答案」。先核对记录，不自动重发。')
    except (URLError, TimeoutError, OSError, ValueError):
        print('未取得完整 JSON。检查网址、证书、网络或流式要求，再到「使用记录」确认，不要连续重发。')
    except (KeyboardInterrupt, EOFError):
        print('\n已停止。若已经确认发送，请先查看使用记录。')
