#!/usr/bin/python3.12
"""批量精简过长摘要（DeepSeek），同步 yes_data + 最终文件"""
import json, urllib.request, time

API_KEY = "sk-00d69ca50b124474b02236121d4cf147"
API_URL = "https://api.deepseek.com/chat/completions"

def call_deepseek(prompt, max_tokens=300):
    payload = json.dumps({
        "model": "deepseek-chat",
        "messages": [{"role": "user", "content": prompt}],
        "max_tokens": max_tokens,
        "temperature": 0.5
    }).encode()
    req = urllib.request.Request(API_URL, data=payload,
        headers={'Authorization': f'Bearer {API_KEY}', 'Content-Type': 'application/json'})
    resp = urllib.request.urlopen(req, timeout=120)
    result = json.loads(resp.read().decode('utf-8'))
    return result['choices'][0]['message']['content'].strip()

# 需要精简的条目（最终文件为基准）：(板块, 索引, 标题, 目标长度)
# social[0] >100字全文重写；social[1]/[2]/[3]/[4]、brand[1]、vehicle[1-4] 精简到 ≤45；
# hyundai domestic[0]/[1] 精简到 35-40
targets = [
    ('brand_hotspots', 1, 'TAMBURINS在HAUS NOWHERE打造13米巨型腊肠犬装置快闪，用仿生机械+AI合影+宠物友好体验，打造沉浸式香氛空间。', 45),
    ('vehicle_hotspots', 1, '近日，新款雷诺5 E?Tech官图发布。新款车型迎来产品升级，从入门版本开始就拥有更高能效、更长续航与更强实用性，同时新增车...', 45),
    ('vehicle_hotspots', 2, '近日，有外媒披露了雷克萨斯RX Morizo RR车型的伪装谍照，新车由丰田GAZOO Racing?打造，定位高性能中大型...', 45),
    ('vehicle_hotspots', 3, '日前，新款林肯冒险家（海外Corsair）混动版官图正式发布，新车将换装2.0T混动系统，综合最大功率305马力，同时外观也...', 45),
    ('vehicle_hotspots', 4, '路虎近期对旗下硬派越野产品线的电动化节奏做出重大调整，原本规划即将亮相的纯电版路虎卫士将延后，最终发布时间直接落到2030年代，...', 45),
    ('social_hotspots', 0, '8月26日深圳特区建立46周年、浦东开发开放36周年；深圳上半年实际使用外资超320亿元、同比增超50%，华强北单日境外客流破8000人次；浦东制度型开放任务落地率超95%，计划2028年服务贸易破1400亿美元。', 55),
    ('social_hotspots', 1, '中科通量推出OmniMate BOX轻量版AI数字员工，采用分体式架构，HDMI直连存量屏幕，搭载12核RISC-V CPU与200 TOPS算力，实现本地闭环，支持闲时广告与忙时服务自动切换。', 45),
    ('social_hotspots', 2, '腾讯汤道生回应AI进展质疑，称混元大模型多次重构且效果突出，但算力不足拖慢训练，强调AI竞赛是马拉松，需熬得久抓住新机遇。', 45),
    ('social_hotspots', 3, '北京人形机器人创新中心CEO熊友军称行业处具身智能ChatGPT前夜，应打造操作系统级底座减少重复建设，中心已有上市计划。', 45),
    ('social_hotspots', 4, '第二届世界人形机器人运动会8月26日在北京闭幕，发布全球首个全量数据集（超2500小时、覆盖12场景），启动五大揭榜计划及进校园活动，第三届定于明年8月举办。', 55),
    ('hyundai_buzz_topics_domestic', 0, '北京现代2026款库斯途上市，13.98万起全系8AT，标配双12.3英寸联屏与电滑门。', 40),
    ('hyundai_buzz_topics_domestic', 1, '起亚2026款嘉华指导价28.89-33.99万，豪华科技款补贴价21.89万，2.0T+8AT。', 40),
]

def get_full_summary(path, k, i):
    d = json.load(open(path))
    if isinstance(d, list):
        for s in d:
            if s.get('name') == k and i < len(s.get('list', [])):
                return s['list'][i].get('summary', '')
    else:
        items = d.get(k, [])
        if i < len(items):
            return items[i].get('summary', '')
    return ''

def set_summary(path, k, i, val):
    d = json.load(open(path))
    if isinstance(d, list):
        for s in d:
            if s.get('name') == k and i < len(s.get('list', [])):
                s['list'][i]['summary'] = val
                break
    else:
        items = d.get(k, [])
        if i < len(items):
            items[i]['summary'] = val
    json.dump(d, open(path, 'w'), ensure_ascii=False, indent=2)

for k, i, title, maxlen in targets:
    full = get_full_summary('/data/news/json/0828data.json', k, i)
    if not full:
        full = title
    prompt = f"""请将下面这条新闻摘要精简为 {maxlen} 字以内的简洁摘要（保留具体数据/动作，去掉冗余修饰，不要以"近日""日前"开头，中文）：

原标题：{title}
原摘要：{full}

精简后摘要："""
    try:
        summ = call_deepseek(prompt)
        summ = summ.replace('\n', '').strip()
        print(f'{k}[{i}] ({len(summ)}字): {summ}')
        set_summary('/data/news/json/yes_data/0827data.json', k, i, summ)
        set_summary('/data/news/json/0828data.json', k, i, summ)
    except Exception as e:
        print(f'{k}[{i}] 失败: {e}')
    time.sleep(1)

print('\n✅ 完成')

# 校验
d = json.load(open('/data/news/json/0828data.json'))
for k in ['brand_hotspots','vehicle_hotspots','social_hotspots','hyundai_buzz_topics_domestic','hyundai_buzz_topics_international']:
    for i, it in enumerate(d.get(k, [])):
        n = len(it.get('summary', ''))
        if n > 55:
            print(f'  ⚠️ [{k}][{i}] {n}字: {it.get("summary","")[:50]}')