#!/usr/bin/env python3
import json
import os
import sys
import urllib.request
import urllib.error

DASHSCOPE_API_KEY = os.getenv('DASHSCOPE_API_KEY')
DASHSCOPE_BASE_URL = os.getenv('DASHSCOPE_BASE_URL', 'https://dashscope.aliyuncs.com/compatible-mode/v1').rstrip('/')
MODEL = os.getenv('TONGYI_SEARCH_MODEL', 'qwen-plus')
GATEWAY_TOKEN = '96ef8f5a66d6a7e39d44b376fe5f9dc318b15fa5c6e1191d'
GATEWAY_BASE = 'http://127.0.0.1:18789'
TARGET = 'user:ou_6dd569a06a6ffc3a417a32f65f374840'
CHANNEL = 'feishu'
SESSION_KEY = 'agent:main:feishu:direct:ou_6dd569a06a6ffc3a417a32f65f374840'


def http_json(url, payload, headers=None, timeout=90):
    data = json.dumps(payload).encode('utf-8')
    req = urllib.request.Request(
        url,
        data=data,
        headers={
            'Content-Type': 'application/json',
            **(headers or {}),
        },
        method='POST',
    )
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        body = resp.read().decode('utf-8')
        return json.loads(body)


def generate_brief():
    if not DASHSCOPE_API_KEY:
        raise RuntimeError('DASHSCOPE_API_KEY 未配置')

    payload = {
        'model': MODEL,
        'messages': [
            {
                'role': 'system',
                'content': (
                    '你是一名主机游戏新闻编辑。请联网搜索并生成一份中文早报。'
                    '重点关注 PlayStation / PS5、Nintendo Switch / 任天堂、Xbox / 微软主机游戏，覆盖第一方与第三方新作、补丁、活动、销量、发售日。'
                    '要求：简洁、可信、适合晨读；不要编造；如果没有重大新闻就明确说明。'
                ),
            },
            {
                'role': 'user',
                'content': (
                    '请生成今天的全主机游戏新闻早报（重点含 PS5、Switch、Xbox）。输出格式严格为：\n'
                    '【今日总览】1-2句\n'
                    '【重点新闻】3-6条，每条 1-3 句\n'
                    '【今天值得关注】列 2-4 个值得关注的主机游戏动态\n'
                    '【一句提醒】给出今天最值得留意的一个方向。'
                ),
            },
        ],
        'enable_search': True,
    }

    result = http_json(
        f'{DASHSCOPE_BASE_URL}/chat/completions',
        payload,
        headers={'Authorization': f'Bearer {DASHSCOPE_API_KEY}'},
        timeout=120,
    )

    content = result['choices'][0]['message']['content']
    if isinstance(content, list):
        text_parts = []
        for item in content:
            if isinstance(item, dict) and item.get('type') == 'text':
                text_parts.append(item.get('text', ''))
            else:
                text_parts.append(str(item))
        content = '\n'.join([p for p in text_parts if p])

    return f'[[reply_to_current]] 大白，全主机游戏早报来了：\n\n{content}'


def send_message(text):
    payload = {
        'tool': 'message',
        'args': {
            'action': 'send',
            'channel': CHANNEL,
            'target': TARGET,
            'message': text,
        },
        'sessionKey': SESSION_KEY,
    }
    return http_json(
        f'{GATEWAY_BASE}/tools/invoke',
        payload,
        headers={'Authorization': f'Bearer {GATEWAY_TOKEN}'},
        timeout=60,
    )


def main():
    try:
        text = generate_brief()
        send_message(text)
        print('OK: brief generated and sent')
    except Exception as e:
        fallback = (
            '[[reply_to_current]] 大白，原定的 PS5 早报生成失败了。\n\n'
            f'错误：{e}\n'
            '你回我一句“补一份PS5早报”，我立刻给你现做。'
        )
        try:
            send_message(fallback)
            print(f'FAILED_BUT_NOTIFIED: {e}')
        except Exception as send_err:
            print(f'FATAL: {e} | notify_failed: {send_err}', file=sys.stderr)
            sys.exit(1)


if __name__ == '__main__':
    main()
