"""从当前YES中按yes_protocol.md选出各板块Top 5 → yes_5_0616data.json"""
import json, os, urllib.request, copy

DEEPSEEK_URL = 'https://api.deepseek.com/v1/chat/completions'
INPUT = '/data/news/json/origin_data/yes_0616data.json'
OUTPUT = '/data/news/json/origin_data/yes_5_0616data.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_TEMPLATE = """你是现代汽车营销情报分析师。请严格按以下规则从{count}条{section}中选出最有价值的5条。

## 评分规则
1. 优先选与汽车消费、用车场景、出行直接相关的内容
2. 其次选能转化为营销动作的热点（体育赛事、消费趋势、跨界合作）
3. 排除：PR软文、疑问句观点文、与汽车无关的纯娱乐八卦
4. 综合分析文章意图，判断是客观报道还是主观推广

## 评分映射
- ≥ 65: strong_select（强烈推荐）
- 45-64: select（推荐）
- 25-44: backup（备选）
- < 25: reject（不推荐）

请按价值从高到低排序，选前5条。输出严格JSON：
[
  {{
    "rank": 1,
    "idx": 序号,
    "overall_score": 0-100,
    "selection_reason": "15字内理由",
    "marketing_opportunity": "20字内启示"
  }},
  ...
]

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

def call_ds(items, section_name):
    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_TEMPLATE.format(
        count=len(items), section=section_name, items_text=items_text)

    payload = json.dumps({
        "model": "deepseek-chat",
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0.3,
        "max_tokens": 2000
    }).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


def main():
    print("=" * 60)
    print("Top 5 精选：按 yes_protocol.md 评分")
    print("=" * 60)
    
    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
        
        all_items = section.get('list', [])
        yes_items = [it for it in all_items if it.get('yesorno') == 'yes']
        
        print("\n【%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:
                # DeepSeek返回了排序结果
                indices = [r.get('idx', 0) for r in results[:5]]
                selected = [yes_items[i-1] for i in indices if 0 <= i-1 < len(yes_items)]
                
                print("  DeepSeek Top 5:")
                for r in results[:5]:
                    idx = r.get('idx', 0)
                    score = r.get('overall_score', 0)
                    reason = r.get('selection_reason', '')
                    if 1 <= idx <= len(yes_items):
                        print("    #%d score=%d %s" % (r.get('rank',0), score, yes_items[idx-1].get('title','')[:40]))
                        print("      理由: %s" % reason[:25])
            else:
                # 降级：取前5条
                print("  ⚠️ DeepSeek返回异常，取前5条")
                selected = yes_items[:5]
        
        # 构建输出section
        result_section = {"name": name, "opinion": "", "list": selected}
        output.append(result_section)
        total += len(selected)
    
    # 补全hyundai板块（原样保留）
    hyundai_sections = ['hyundai_buzz_topics_domestic', 'hyundai_buzz_topics_international']
    for name in hyundai_sections:
        for section in data:
            if section.get('name') == name and section not in output:
                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" + "=" * 60)
    print("✅ 已保存 %s" % OUTPUT)
    print("各板块 Top 5:")
    for section in output:
        name = section.get('name', '')
        items = section.get('list', [])
        if name in ('brand_hotspots', 'vehicle_hotspots', 'social_hotspots'):
            print("  %s: %d条" % (name, len(items)))
        else:
            print("  %s: %d条（原样保留）" % (name, len(items)))
    print("总计: %d条" % total)

if __name__ == '__main__':
    main()
