import json, os, urllib.request, copy

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

def get_ds_key():
    try:
        with open('/root/.openclaw/openclaw.json') as f:
            return json.load(f)['models']['providers']['deepseek']['apiKey']
    except:
        return None

PROMPT = """你是现代汽车营销情报分析师。请从以下{count}条{section}中选出最有营销启示价值的Top 5。

## 规则
1. 优先选与汽车消费/出行/用车场景直接相关的内容
2. 其次选能转化为营销动作的热点（体育赛事、消费趋势、跨界合作）
3. 排除：PR软文、疑问句观点文
4. 车型板块：有具体车型的营销模式创新权重最高

## 输出前5条，按价值排序，每条含完整7维评分

输出格式：
[{{"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":["无明显风险"],"confidence":0.85}},...]

待评{section}：
{items_text}"""

def call_ds(items, section):
    key = get_ds_key()
    if not key: return None
    lines = []
    for i, it in enumerate(items, 1):
        lines.append("[%d] 标题：%s" % (i, it.get('title','')))
        lines.append("    摘要：%s" % it.get('summary',''))
        lines.append("    品牌：%s" % it.get('brand',''))
    items_text = '\n'.join(lines)
    prompt = PROMPT.format(count=len(items), section=section, items_text=items_text)
    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'})
    try:
        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: return json.loads(reply[js:je])
        return None
    except Exception as e:
        print("  ❌ %s" % e); return None

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

output = []; total = 0

for section in data:
    name = section.get('name', '')
    if name not in ('brand_hotspots','vehicle_hotspots','social_hotspots'):
        output.append(copy.deepcopy(section)); continue
    items = section.get('list', [])
    yes_items = [it for it in items if it.get('yesorno') == 'yes']
    
    print("【%s】%d条 → 选Top 5..." % (name, len(yes_items)))
    
    if len(yes_items) <= 5:
        print("  ≤5条，全部保留"); selected = yes_items
    else:
        results = call_ds(yes_items, name)
        if results and len(results) >= 5:
            selected = []
            for r in results[:5]:
                idx = r.get('idx',1)-1
                if 0 <= idx < len(yes_items):
                    it = yes_items[idx]
                    s = r.get('scores',{})
                    it['protocol_scores'] = s
                    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)
                    print("  #%d overall=%-3s %s" % (r.get('rank'), s.get('overall_tag_value_score','?'), it.get('title','')[:40]))
                    if r.get('selection_reason'):
                        print("      理由: %s" % r['selection_reason'][:25])
        else:
            print("  ⚠️ 返回异常，取前5"); selected = yes_items[:5]
    
    output.append({"name":name,"opinion":"","list":selected})
    total += len(selected)

for hn in ['hyundai_buzz_topics_domestic','hyundai_buzz_topics_international']:
    for section in data:
        if section.get('name') == hn:
            output.append(copy.deepcopy(section)); break

with open(OUTPUT,'w',encoding='utf-8') as f:
    json.dump(output,f,ensure_ascii=False,indent=2)
print("\n✅ 已保存 %s" % OUTPUT)
print("总计: %d条" % total)
