import json, urllib.request, copy

DEEPSEEK_URL = 'https://api.deepseek.com/v1/chat/completions'
INPUT = '/data/news/json/origin_data/yes_0621data.json'
OUTPUT = '/data/news/json/origin_data/yes_tmp5_0621data.json'

with open('/root/.openclaw/openclaw.json') as f:
    key = json.load(f)['models']['providers']['deepseek']['apiKey']

with open(INPUT, 'r', encoding='utf-8') as f:
    data = json.load(f)

social_items = None
for section in data:
    if section.get('name') == 'social_hotspots':
        social_items = [it for it in section.get('list', []) if it.get('yesorno') == 'yes']
        break

lines = []
for i, it in enumerate(social_items, 1):
    lines.append("[%d] 标题：%s" % (i, it.get('title','')))
    lines.append("    热度：%s" % it.get('heat_score',''))

prompt = """从以下%d条社会热点中选出最有营销启示价值的Top 5。

规则：
1. 优先选与汽车消费/出行/用车场景直接相关的
2. 其次选能转化为营销动作的（体育赛事、消费趋势等）
3. 排除具体车型内容、纯娱乐八卦、与中国无关的政治新闻
4. 同品牌事件不重复

输出JSON数组，按价值排序：
[{"rank":1,"idx":序号,"scores":{"hyundai_relevance_score":0,"conversion_value_score":0,"marketing_actionability_score":0,"brand_influence_score":0,"customer_loyalty_score":0,"competitor_threat_score":0,"overall_tag_value_score":0},"selection_reason":"15字内","marketing_opportunity":"20字内","event_type":"","business_tags":[],"risk_tags":["无明显风险"]},...]

%s""" % (len(social_items), '\n'.join(lines))

payload = json.dumps({"model":"deepseek-chat","messages":[{"role":"user","content":prompt}],"temperature":0.3,"max_tokens":3000}).encode()
req = urllib.request.Request(DEEPSEEK_URL, data=payload, headers={'Authorization':'Bearer '+key,'Content-Type':'application/json'})
resp = urllib.request.urlopen(req, timeout=90)
reply = json.loads(resp.read().decode('utf-8'))['choices'][0]['message']['content'].strip()
js = reply.find('['); je = reply.rfind(']')+1
if js>=0 and je>js:
    results = json.loads(reply[js:je])
    selected = []
    print("social Top 5:\n")
    for r in results[:5]:
        idx = r.get('idx',1)-1
        if 0 <= idx < len(social_items):
            it = copy.deepcopy(social_items[idx])
            it['yesorno'] = 'yes'
            it['protocol_scores'] = r.get('scores',{})
            it['selection_reason'] = r.get('selection_reason','')
            it['marketing_opportunity'] = r.get('marketing_opportunity','')
            it['event_type'] = r.get('event_type','')
            it['business_tags'] = r.get('business_tags',[])
            selected.append(it)
            s = r.get('scores',{})
            print("  #%d overall=%-3s %s" % (r.get('rank'), s.get('overall_tag_value_score','?'), it.get('title','')[:45]))
            if r.get('selection_reason'):
                print("      理由: %s" % r['selection_reason'][:25])
            print()
    
    output_data = [{"name":"social_hotspots","opinion":"","list":selected}]
    with open(OUTPUT,'w',encoding='utf-8') as f:
        json.dump(output_data,f,ensure_ascii=False,indent=2)
    print("✅ 已保存 %s" % OUTPUT)
else:
    print("❌ 解析失败")
