#!/usr/bin/env python3.12
# -*- coding: utf-8 -*-
"""用户修复：brand→GUCCI + focus_point 按 skill 格式重生成"""
import json, re, urllib.request, yaml

# ── 读 DeepSeek key ──
key = None
try:
    with open('/root/.openclaw/openclaw.json') as f:
        key = json.load(f).get('api_key')
except Exception:
    pass
if not key:
    cfg = yaml.safe_load(open('/home/ubuntu/.hermes/config.yaml'))
    key = cfg['providers']['deepseek']['api_key']

DEEPSEEK_API_URL = 'https://api.deepseek.com/chat/completions'

def gen_focus_point(title, summary):
    prompt = ('根据以下新闻，为现代汽车写一条策略启示（focus_point）。要求：不超过35个汉字，措辞柔和，'
              '以"可借鉴""可参考""不妨""建议"等友好语气开头，避免生硬祈使句和"应"字。只输出JSON：{"focus_point": ""}\n\n'
              f'标题：{title}\n摘要：{summary or title}')
    payload = json.dumps({
        "model": "deepseek-chat",
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0.3,
        "max_tokens": 200
    }).encode()
    req = urllib.request.Request(DEEPSEEK_API_URL, data=payload,
        headers={'Authorization': f'Bearer {key}', 'Content-Type': 'application/json'})
    resp = urllib.request.urlopen(req, timeout=60)
    data = json.loads(resp.read().decode())
    content = data['choices'][0]['message']['content']
    m = re.search(r'"focus_point"\s*:\s*"([^"]+)"', content)
    if m:
        return m.group(1)
    return content.strip().strip('{}"')

# ── 1. brand[0] → GUCCI ──
def set_brand(path, sec, idx, brand, is_final=False):
    d = json.load(open(path))
    if is_final:
        if sec in d and idx < len(d[sec]):
            d[sec][idx]['brand'] = brand
    else:
        for s in d:
            if s.get('name') == sec and idx < len(s['list']):
                s['list'][idx]['brand'] = brand
                break
    json.dump(d, open(path, 'w'), ensure_ascii=False, indent=2)
    print(f'  ✅ {path} brand[{idx}] → {brand}')

set_brand('/data/news/json/yes_data/0821data.json', 'brand_hotspots', 0, 'GUCCI')
set_brand('/data/news/json/0822data.json', 'brand_hotspots', 0, 'GUCCI', is_final=True)

# ── 2. focus_point 重生成（品牌5条 + 车型[3]）──
# 从最终文件读标题/summary
fin = json.load(open('/data/news/json/0822data.json'))

fp_targets = []  # (sec, idx, title, summary)
for i, it in enumerate(fin.get('brand_hotspots', [])):
    fp_targets.append(('brand_hotspots', i, it.get('title',''), it.get('summary','')))
fp_targets.append(('vehicle_hotspots', 3,
                   fin['vehicle_hotspots'][3].get('title',''),
                   fin['vehicle_hotspots'][3].get('summary','')))

new_fps = {}
for sec, idx, title, summary in fp_targets:
    try:
        fp = gen_focus_point(title, summary)
        new_fps[(sec, idx)] = fp
        content_len = len(re.sub(r'[；，。、：""''（）()]', '', fp))
        print(f'  ✅ {sec}[{idx}] → {fp} ({content_len}字)')
    except Exception as e:
        print(f'  ❌ {sec}[{idx}] 失败: {e}')

# 写入 yes_data + 最终文件
for path, is_final in [('/data/news/json/yes_data/0821data.json', False), ('/data/news/json/0822data.json', True)]:
    d = json.load(open(path))
    for (sec, idx), fp in new_fps.items():
        if is_final:
            if sec in d and idx < len(d[sec]):
                d[sec][idx]['focus_point'] = fp
        else:
            for s in d:
                if s.get('name') == sec and idx < len(s['list']):
                    s['list'][idx]['focus_point'] = fp
                    break
    json.dump(d, open(path, 'w'), ensure_ascii=False, indent=2)
    print(f'  ✅ 已写入 {path}')

print('\n✅ focus_point 重生成完成')
