import json, os, urllib.request, copy

DEEPSEEK_URL = 'https://api.deepseek.com/v1/chat/completions'
INPUT = '/data/news/json/origin_data/yes_0617data.json'
OUTPUT = '/data/news/json/origin_data/yes_5_0617data.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条，按价值从高到低排序

## 输出格式（严格JSON数组，完整字段）
[
  {{
    "rank": 1,
    "idx": 序号,
    "scores": {{
      "hyundai_relevance_score": 0-100,
      "conversion_value_score": 0-100,
      "marketing_actionability_score": 0-100,
      "brand_influence_score": 0-100,
      "customer_loyalty_score": 0-100,
      "competitor_threat_score": 0-100,
      "overall_tag_value_score": 0-100
    }},
    "selection_suggestion": "",
    "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', ''))
        s = it.get('protocol_scores', {})
        lines.append("    当前评分：overall=%s" % s.get('overall_tag_value_score', ''))
    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()
        json_start = reply.find('[')
        json_end = reply.rfind(']') + 1
        if json_start >= 0 and json_end > json_start:
            return json.loads(reply[json_start:json_end])
        print("  ⚠️ 解析失败: %s" % reply[:150])
        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】YES %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:
            indices = [r.get('idx', 0) for r in results[:5]]
            selected = []
            for r in results[:5]:
                idx = r.get('idx', 1) - 1
                if 0 <= idx < len(yes_items):
                    item = yes_items[idx]
                    s = r.get('scores', {})
                    item['protocol_scores'] = s
                    item['selection_suggestion'] = r.get('selection_suggestion','')
                    item['selection_reason'] = r.get('selection_reason','')
                    item['marketing_opportunity'] = r.get('marketing_opportunity','')
                    item['event_type'] = r.get('event_type','')
                    item['business_tags'] = r.get('business_tags',[])
                    item['risk_tags'] = r.get('risk_tags',[])
                    item['confidence'] = r.get('confidence', 0.85)
                    selected.append(item)
                    print("  #%d overall=%-3s %s" % (r.get('rank'), s.get('overall_tag_value_score','?'), item.get('title','')[:40]))
                    if r.get('selection_reason'):
                        print("      理由: %s" % r['selection_reason'][:25])
        else:
            print("  ⚠️ DeepSeek返回异常，取前5条")
            selected = yes_items[:5]
    
    output.append({"name": name, "opinion": "", "list": selected})
    total += len(selected)

# 补全hyundai
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)
