"""完整协议评分：输出 yes_protocol.md 全部字段（含多维评分、标签、理由）"""
import json, os, urllib.request, copy
from datetime import datetime

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

PROTOCOL_PROMPT = """你是现代汽车营销情报分析师。请严格按以下规则对{count}条{section}进行评分。

## 决策规则
1. 优先选与汽车消费、用车场景、出行相关的话题
2. 其次选能转化为营销动作的热点（体育赛事、消费趋势、跨界合作）
3. 再次选具有高话题度的社会事件（可能适合借势）
4. 排除：PR软文、疑问句观点文、纯娱乐八卦、政治敏感

## 车型板块特殊规则（权重最高）
- 有具体车型的营销模式创新（直播带货/跨界破圈/新零售/主播试驾等）评分最高
- 领导特别关注此类内容

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

## 请按价值从高到低排序，输出前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": "品牌营销案例 | 竞品上市 | 竞品预售 | 竞品降价 | 世界杯体育营销 | 体育营销 | 社会热点 | 技术合作 | 明星代言 | 私域运营 | 其他",
    "industry_tags": [],
    "business_tags": [],
    "marketing_tags": [],
    "target_user_tags": [],
    "risk_tags": ["无明显风险"],
    "confidence": 0.85
  }},
  ...
]

待评{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 = PROTOCOL_PROMPT.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": 4000
    }).encode()
    
    req = urllib.request.Request(DEEPSEEK_URL, data=payload,
        headers={'Authorization': 'Bearer ' + key, 'Content-Type': 'application/json'})
    try:
        resp = urllib.request.urlopen(req, timeout=120)
        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("  ⚠️ 解析失败，原始返回前200字:")
        print("  %s" % reply[:200])
        return None
    except Exception as e:
        print("  ❌ %s" % e)
        return None


def main():
    print("=" * 70)
    print("完整协议评分（yes_protocol.md 全字段输出）")
    print("=" * 70)
    
    with open(INPUT, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    output = []
    
    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条 → DeepSeek 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 = []
                
                print("\n  DeepSeek评分详情:")
                print("-" * 70)
                for r in results[:5]:
                    idx = r.get('idx', 1) - 1
                    if 0 <= idx < len(yes_items):
                        item = yes_items[idx]
                        scores = r.get('scores', {})
                        
                        # 将协议评分字段写入item
                        item['protocol_scores'] = scores
                        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['industry_tags'] = r.get('industry_tags', [])
                        item['business_tags'] = r.get('business_tags', [])
                        item['marketing_tags'] = r.get('marketing_tags', [])
                        item['target_user_tags'] = r.get('target_user_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', 0), 
                            scores.get('overall_tag_value_score', '?'), item.get('title','')[:40]))
                        print("     多维评分: H=%-2d C=%-2d M=%-2d B=%-2d L=%-2d T=%-2d" % (
                            scores.get('hyundai_relevance_score',0),
                            scores.get('conversion_value_score',0),
                            scores.get('marketing_actionability_score',0),
                            scores.get('brand_influence_score',0),
                            scores.get('customer_loyalty_score',0),
                            scores.get('competitor_threat_score',0)))
                        print("     建议: %s  理由: %s" % (r.get('selection_suggestion',''), r.get('selection_reason','')))
                        print("     启示: %s" % r.get('marketing_opportunity',''))
                        print("     类型: %s  业务标签: %s" % (r.get('event_type',''), ','.join(r.get('business_tags',[]))))
                        print()
            else:
                print("  ⚠️ 返回异常，取前5条")
                selected = yes_items[:5]
        
        # 清理协议字段（保留在数据中供后续参考）
        result_section = {"name": name, "opinion": "", "list": selected}
        output.append(result_section)
    
    # 补全hyundai
    hyundai_names = ['hyundai_buzz_topics_domestic', 'hyundai_buzz_topics_international']
    for hn in hyundai_names:
        for section in data:
            if section.get('name') == hn 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("=" * 70)
    print("✅ 已保存 %s" % OUTPUT)
    print("=" * 70)


if __name__ == '__main__':
    main()
